diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml new file mode 100644 index 0000000..be934dd --- /dev/null +++ b/.github/workflows/validate.yml @@ -0,0 +1,19 @@ +name: Validate desktop +on: + push: + pull_request: +permissions: + contents: read +jobs: + checks: + runs-on: windows-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 24 + cache: npm + - run: npm ci + - run: npm run typecheck + - run: npm run lint + - run: npm test diff --git a/.gitignore b/.gitignore index 8296128..5c7ae90 100644 --- a/.gitignore +++ b/.gitignore @@ -90,3 +90,6 @@ typings/ # Electron-Forge out/ + +# Local release tooling and verification results +.release-work/ diff --git a/README.md b/README.md index 0024f72..db32c5a 100644 --- a/README.md +++ b/README.md @@ -99,13 +99,13 @@ The desktop app checks the hosted Projecto website for update metadata. The webs Current desktop build target: -- Version: `1.0.7` -- Installer: `Projecto-1.0.7.Setup.exe` +- Version: `1.0.8` +- Installer: `Projecto-1.0.8.Setup.exe` - Release feed: GitHub Releases - Windows maker: Squirrel.Windows through Electron Forge The download page and update API are maintained in `D:\projecto_frontend` and -must be updated when the `1.0.7` artifacts are published. +must be updated when the `1.0.8` artifacts are published. ## Setup diff --git a/assets/icon.icns b/assets/icon.icns new file mode 100644 index 0000000..4c2b395 Binary files /dev/null and b/assets/icon.icns differ diff --git a/assets/icon.ico b/assets/icon.ico index fcdda57..0f252ee 100644 Binary files a/assets/icon.ico and b/assets/icon.ico differ diff --git a/assets/icon.png b/assets/icon.png new file mode 100644 index 0000000..a3c56e3 Binary files /dev/null and b/assets/icon.png differ diff --git a/docs/releases/1.0.8.md b/docs/releases/1.0.8.md new file mode 100644 index 0000000..02fc0e0 --- /dev/null +++ b/docs/releases/1.0.8.md @@ -0,0 +1,37 @@ +# Projecto 1.0.8 + +Projecto 1.0.8 refreshes the desktop identity throughout the packaged app and +Squirrel.Windows release. + +## Highlights + +- Adds a high-resolution Projecto app icon for Linux and other PNG consumers. +- Adds a multi-size Windows icon for the executable and Squirrel installer. +- Adds a macOS icon bundle for future signed and notarized builds. +- Uses the branded icon for native app windows and taskbar entries. +- Keeps the Projecto website favicon visually identical to the desktop app. + +## Validation + +- TypeScript typecheck: passed. +- ESLint: passed. +- Desktop tests: 103 passed across 19 files. +- Squirrel.Windows make: passed. +- Packaged executable file and product version: `1.0.8`. + +## Windows release assets + +| Artifact | Bytes | SHA-256 | +| --- | ---: | --- | +| `Projecto-1.0.8.Setup.exe` | `138862080` | `b1f26e9ef060eb05d424321c0501e1894c84f10b372b6c1a3cdbad7fa34a4bc3` | +| `projecto-1.0.8-full.nupkg` | `138043457` | `f890cb3d66ca6c3354e30f0cdac3da8358c4c9dbc0bdc7dffa9f4594a956af35` | + +The generated `RELEASES` entry is: + +```text +AFBCCC7614B44109BDB5A1F415CED7FB7C876412 projecto-1.0.8-full.nupkg 138043457 +``` + +The current Windows installer is unsigned. Configure one of the supported +Windows signing environment-variable sets in `forge.config.js` and rebuild to +avoid Windows SmartScreen publisher warnings. diff --git a/eslint.config.mjs b/eslint.config.mjs index 59110cf..823ff89 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -6,7 +6,7 @@ import tseslint from 'typescript-eslint'; export default [ { - ignores: ['.webpack/**', 'out/**', 'node_modules/**'], + ignores: ['.webpack/**', '.release-work/**', 'out/**', 'node_modules/**'], }, { files: ['**/*.{js,mjs,cjs,ts,tsx}'], @@ -39,7 +39,7 @@ export default [ }, }, { - files: ['forge.config.js', 'webpack.*.js', 'tailwind.config.js', 'postcss.config.js'], + files: ['forge.config.js', 'webpack.*.js', 'tailwind.config.js', 'postcss.config.js', 'vendor/projecto-protocol/index.js'], rules: { '@typescript-eslint/no-require-imports': 'off', }, diff --git a/package-lock.json b/package-lock.json index 5a2aa47..f472aed 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "projecto", - "version": "1.0.7", + "version": "1.0.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "projecto", - "version": "1.0.7", + "version": "1.0.9", "license": "MIT", "dependencies": { "@fontsource-variable/inter-tight": "^5.3.0", @@ -21,7 +21,7 @@ "framer-motion": "^12.38.0", "gsap": "^3.15.0", "lucide-react": "^0.468.0", - "projecto-protocol": "file:../projecto-protocol", + "projecto-protocol": "file:vendor/projecto-protocol", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.28.0", @@ -64,13 +64,6 @@ "webpack-cli": "^6.0.1" } }, - "../projecto-protocol": { - "version": "0.1.0", - "license": "MIT", - "dependencies": { - "zod": "^3.23.8" - } - }, "node_modules/@alloc/quick-lru": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", @@ -2927,9 +2920,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3656,9 +3646,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3673,9 +3660,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3690,9 +3674,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3707,9 +3688,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3724,9 +3702,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3741,9 +3716,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3758,9 +3730,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3775,9 +3744,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3792,9 +3758,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3809,9 +3772,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3826,9 +3786,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3843,9 +3800,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3860,9 +3814,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -13340,7 +13291,7 @@ } }, "node_modules/projecto-protocol": { - "resolved": "../projecto-protocol", + "resolved": "vendor/projecto-protocol", "link": true }, "node_modules/promise-inflight": { @@ -17076,6 +17027,13 @@ "optional": true } } + }, + "vendor/projecto-protocol": { + "version": "0.1.0", + "license": "MIT", + "dependencies": { + "zod": "^3.23.8" + } } } } diff --git a/package.json b/package.json index 355e2ef..768d98b 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "projecto", "productName": "Projecto", - "version": "1.0.7", + "version": "1.0.9", "description": "An Electron desktop app for managing, syncing, and launching developer projects through the Projecto platform.", "main": ".webpack/main", "private": true, @@ -34,7 +34,7 @@ "framer-motion": "^12.38.0", "gsap": "^3.15.0", "lucide-react": "^0.468.0", - "projecto-protocol": "file:../projecto-protocol", + "projecto-protocol": "file:vendor/projecto-protocol", "react": "^18.2.0", "react-dom": "^18.2.0", "react-router-dom": "^6.28.0", diff --git a/src/main/index.ts b/src/main/index.ts index 16c6c6c..4755c19 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -123,9 +123,7 @@ function shutdownServices(): Promise { } shutdownPromise = (async () => { - await runShutdownStep("launcher", () => { - launcherService?.stopAllRuns(); - }); + await runShutdownStep("launcher", () => launcherService?.stopAllRuns()); await runShutdownStep("terminal compatibility", async () => { await desktopBridgeService?.stop(); }); @@ -323,7 +321,7 @@ async function bootstrapIpc( ); const settings = await settingsStore.getSettings(); await syncOpenAtLogin(settings.launchOnStartup); - await subscriptionService.initialize(); + void subscriptionService.initialize().catch((error) => logMainProcessError("Initial subscription verification failed", error)); await desktopBridgeService.start(); launcherService = new LauncherService( diff --git a/src/main/ipc/billing.ipc.ts b/src/main/ipc/billing.ipc.ts index 72e45ad..f61d10f 100644 --- a/src/main/ipc/billing.ipc.ts +++ b/src/main/ipc/billing.ipc.ts @@ -1,23 +1,24 @@ -import { ipcMain } from "electron"; +import { handleTrusted } from "./trustedSender"; + import { SubscriptionService } from "../services/subscriptionService"; export function registerBillingIpc( subscriptionService: SubscriptionService, ): void { - ipcMain.handle("billing:getSubscriptionState", async () => { + handleTrusted("billing:getSubscriptionState", async () => { return subscriptionService.getSubscriptionState(); }); - ipcMain.handle("billing:openUpgradePage", async () => { + handleTrusted("billing:openUpgradePage", async () => { await subscriptionService.openUpgradePage(); }); - ipcMain.handle("billing:startGoogleSignIn", async () => { + handleTrusted("billing:startGoogleSignIn", async () => { await subscriptionService.startGoogleSignIn(); }); - ipcMain.handle("billing:refreshSubscription", async () => { + handleTrusted("billing:refreshSubscription", async () => { return subscriptionService.refreshSubscription(); }); } diff --git a/src/main/ipc/diagnostics.ipc.ts b/src/main/ipc/diagnostics.ipc.ts index cdebece..de19ae9 100644 --- a/src/main/ipc/diagnostics.ipc.ts +++ b/src/main/ipc/diagnostics.ipc.ts @@ -1,9 +1,10 @@ +import { handleTrusted } from "./trustedSender"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { spawn } from "node:child_process"; -import { app, clipboard, dialog, ipcMain, shell } from "electron"; +import { app, clipboard, dialog, shell } from "electron"; import { PROTOCOL_VERSION } from "projecto-protocol"; import { DiagnosticCheckResultSchema, @@ -274,15 +275,15 @@ export function registerDiagnosticsIpc({ }); } - ipcMain.handle("diagnostics:getReport", async () => buildReport()); + handleTrusted("diagnostics:getReport", async () => buildReport()); - ipcMain.handle("diagnostics:getRunningPorts", async () => getRunningPorts()); + handleTrusted("diagnostics:getRunningPorts", async () => getRunningPorts()); - ipcMain.handle("diagnostics:copyReport", async () => { + handleTrusted("diagnostics:copyReport", async () => { clipboard.writeText(stringifyReport(await buildReport())); }); - ipcMain.handle("diagnostics:exportReport", async () => { + handleTrusted("diagnostics:exportReport", async () => { const report = await buildReport(); const result = await dialog.showSaveDialog({ title: "Export Projecto diagnostics", @@ -300,7 +301,7 @@ export function registerDiagnosticsIpc({ await fs.writeFile(result.filePath, stringifyReport(report), "utf8"); }); - ipcMain.handle("diagnostics:openAppDataFolder", async () => { + handleTrusted("diagnostics:openAppDataFolder", async () => { const result = await shell.openPath(app.getPath("userData")); if (result) { @@ -308,7 +309,7 @@ export function registerDiagnosticsIpc({ } }); - ipcMain.handle("diagnostics:testEditor", async () => { + handleTrusted("diagnostics:testEditor", async () => { await settingsStore.getSettings(); const command = resolveEditorCommand(); const ok = await commandStarts(command); @@ -321,7 +322,7 @@ export function registerDiagnosticsIpc({ }); }); - ipcMain.handle("diagnostics:testTerminal", async () => { + handleTrusted("diagnostics:testTerminal", async () => { const command = process.platform === "win32" ? process.env.ComSpec?.trim() || "cmd.exe" @@ -340,7 +341,7 @@ export function registerDiagnosticsIpc({ }); }); - ipcMain.handle("diagnostics:resetCommandApprovals", async () => { + handleTrusted("diagnostics:resetCommandApprovals", async () => { await commandSafetyService.resetApprovals(); }); } diff --git a/src/main/ipc/insights.ipc.ts b/src/main/ipc/insights.ipc.ts index 0025482..4dd18fa 100644 --- a/src/main/ipc/insights.ipc.ts +++ b/src/main/ipc/insights.ipc.ts @@ -1,4 +1,5 @@ -import { ipcMain } from "electron"; +import { handleTrusted } from "./trustedSender"; + import { ActivityStore } from "../services/activityStore"; import { ProjectStore } from "../services/projectStore"; @@ -12,7 +13,7 @@ export function registerInsightsIpc({ activityStore, projectStore, }: RegisterInsightsIpcOptions): void { - ipcMain.handle("insights:getUsageStats", async () => { + handleTrusted("insights:getUsageStats", async () => { try { const projects = await projectStore.getProjects({ persistLocalDetails: false, diff --git a/src/main/ipc/launcher.ipc.ts b/src/main/ipc/launcher.ipc.ts index 3ba9612..c0732df 100644 --- a/src/main/ipc/launcher.ipc.ts +++ b/src/main/ipc/launcher.ipc.ts @@ -1,8 +1,9 @@ +import { handleTrusted } from "./trustedSender"; import fs from "node:fs/promises"; import os from "node:os"; import path from "node:path"; -import { dialog, ipcMain } from "electron"; +import { dialog } from "electron"; import { z } from "zod"; import { ExportRunLogsInputSchema } from "../types/shared"; @@ -23,15 +24,15 @@ export function registerLauncherIpc( launcherService: LauncherService, desktopBridgeService: DesktopBridgeService, ): void { - ipcMain.handle("launcher:openFolder", async (_event, input) => { + handleTrusted("launcher:openFolder", async (_event, input) => { await launcherService.openFolder(pathSchema.parse(input)); }); - ipcMain.handle("launcher:openEditor", async (_event, input) => { + handleTrusted("launcher:openEditor", async (_event, input) => { await launcherService.openEditor(idSchema.parse(input)); }); - ipcMain.handle( + handleTrusted( "launcher:launchProfile", async (_event, projectId, profileId, options) => { return launcherService.launchProfile( @@ -42,7 +43,7 @@ export function registerLauncherIpc( }, ); - ipcMain.handle( + handleTrusted( "launcher:runCommand", async (_event, projectId, commandId, options) => { return launcherService.runCommand( @@ -53,38 +54,38 @@ export function registerLauncherIpc( }, ); - ipcMain.handle("launcher:openUrl", async (_event, input) => { + handleTrusted("launcher:openUrl", async (_event, input) => { await launcherService.openUrl(urlSchema.parse(input)); }); - ipcMain.handle("launcher:stopRun", async (_event, runId) => { + handleTrusted("launcher:stopRun", async (_event, runId) => { return launcherService.stopRun(idSchema.parse(runId)); }); - ipcMain.handle("launcher:stopProjectTerminal", async (_event, projectId) => { + handleTrusted("launcher:stopProjectTerminal", async (_event, projectId) => { return launcherService.stopProjectTerminal(idSchema.parse(projectId)); }); - ipcMain.handle( + handleTrusted( "launcher:revealProjectTerminal", async (_event, projectId) => { return launcherService.revealProjectTerminal(idSchema.parse(projectId)); }, ); - ipcMain.handle("launcher:getTerminalSessions", async () => { + handleTrusted("launcher:getTerminalSessions", async () => { return launcherService.getTerminalSessions(); }); - ipcMain.handle("launcher:getBridgeState", async () => + handleTrusted("launcher:getBridgeState", async () => desktopBridgeService.getState(), ); - ipcMain.handle("launcher:getCommandSafety", async (_event, projectId) => { + handleTrusted("launcher:getCommandSafety", async (_event, projectId) => { return launcherService.getCommandSafety(idSchema.parse(projectId)); }); - ipcMain.handle("launcher:exportRunLogs", async (_event, input) => { + handleTrusted("launcher:exportRunLogs", async (_event, input) => { const payload = ExportRunLogsInputSchema.parse(input); const safeTitle = payload.title.replace(/[<>:"/\\|?*]+/g, "-").slice(0, 80); const result = await dialog.showSaveDialog({ diff --git a/src/main/ipc/maintenance.ipc.ts b/src/main/ipc/maintenance.ipc.ts index c534e17..d9481f0 100644 --- a/src/main/ipc/maintenance.ipc.ts +++ b/src/main/ipc/maintenance.ipc.ts @@ -1,14 +1,15 @@ -import { ipcMain } from "electron"; +import { handleTrusted } from "./trustedSender"; + import { MaintenanceService } from "../services/maintenanceService"; export function registerMaintenanceIpc( maintenanceService: MaintenanceService, ): void { - ipcMain.handle("maintenance:getStatus", async () => + handleTrusted("maintenance:getStatus", async () => maintenanceService.getStatus(), ); - ipcMain.handle("maintenance:cleanup", async () => + handleTrusted("maintenance:cleanup", async () => maintenanceService.runCleanup("manual"), ); } diff --git a/src/main/ipc/project.ipc.ts b/src/main/ipc/project.ipc.ts index 4dca9b1..5185a84 100644 --- a/src/main/ipc/project.ipc.ts +++ b/src/main/ipc/project.ipc.ts @@ -1,4 +1,5 @@ -import { dialog, ipcMain, type OpenDialogOptions } from "electron"; +import { handleTrusted } from "./trustedSender"; +import { dialog, type OpenDialogOptions } from "electron"; import { z } from "zod"; import { @@ -30,7 +31,7 @@ export function registerProjectIpc({ activityStore, subscriptionService, }: RegisterProjectIpcOptions): void { - ipcMain.handle("projects:selectFolder", async () => { + handleTrusted("projects:selectFolder", async () => { const window = getMainWindow(); const options: OpenDialogOptions = { title: "Select a project folder", @@ -47,11 +48,11 @@ export function registerProjectIpc({ return result.filePaths[0] ?? null; }); - ipcMain.handle("projects:scanFolder", async (_event, input) => { + handleTrusted("projects:scanFolder", async (_event, input) => { return projectScanner.scanFolder(pathSchema.parse(input)); }); - ipcMain.handle("projects:scanWorkspace", async (_event, input) => { + handleTrusted("projects:scanWorkspace", async (_event, input) => { const subscription = await subscriptionService.getSubscriptionState(); if (!canUseBulkImport(subscription)) { @@ -61,15 +62,15 @@ export function registerProjectIpc({ return projectScanner.scanWorkspace(pathSchema.parse(input)); }); - ipcMain.handle("projects:getProjects", async () => { + handleTrusted("projects:getProjects", async () => { return projectStore.getProjects(); }); - ipcMain.handle("projects:getProject", async (_event, input) => { + handleTrusted("projects:getProject", async (_event, input) => { return projectStore.getProject(idSchema.parse(input)); }); - ipcMain.handle("projects:createProject", async (_event, input) => { + handleTrusted("projects:createProject", async (_event, input) => { const project = await projectStore.createProject( CreateProjectInputSchema.parse(input), ); @@ -82,7 +83,7 @@ export function registerProjectIpc({ return project; }); - ipcMain.handle("projects:bulkImportProjects", async (_event, input) => { + handleTrusted("projects:bulkImportProjects", async (_event, input) => { const payload = bulkImportSchema.parse(input); const projects = await projectStore.bulkImportProjects(payload); @@ -100,18 +101,18 @@ export function registerProjectIpc({ return projects; }); - ipcMain.handle("projects:updateProject", async (_event, id, patch) => { + handleTrusted("projects:updateProject", async (_event, id, patch) => { const projectId = idSchema.parse(id); const payload = ProjectUpdateSchema.parse(patch); return projectStore.updateProject(projectId, payload); }); - ipcMain.handle("projects:deleteProject", async (_event, input) => { + handleTrusted("projects:deleteProject", async (_event, input) => { await projectStore.deleteProject(idSchema.parse(input)); }); - ipcMain.handle("projects:toggleFavorite", async (_event, input) => { + handleTrusted("projects:toggleFavorite", async (_event, input) => { return projectStore.toggleFavorite(idSchema.parse(input)); }); } diff --git a/src/main/ipc/settings.ipc.ts b/src/main/ipc/settings.ipc.ts index ff49f6d..6c3cd82 100644 --- a/src/main/ipc/settings.ipc.ts +++ b/src/main/ipc/settings.ipc.ts @@ -1,4 +1,5 @@ -import { ipcMain } from "electron"; +import { handleTrusted } from "./trustedSender"; + import type { AppSettings } from "../types/shared"; import { AppSettingsUpdateSchema } from "../types/shared"; @@ -8,11 +9,11 @@ export function registerSettingsIpc( settingsStore: SettingsStore, onSettingsUpdated?: (settings: AppSettings) => Promise | void, ): void { - ipcMain.handle("settings:getSettings", async () => { + handleTrusted("settings:getSettings", async () => { return settingsStore.getSettings(); }); - ipcMain.handle("settings:updateSettings", async (_event, patch) => { + handleTrusted("settings:updateSettings", async (_event, patch) => { const payload = AppSettingsUpdateSchema.parse(patch); const settings = await settingsStore.updateSettings(payload); await onSettingsUpdated?.(settings); diff --git a/src/main/ipc/trustedSender.ts b/src/main/ipc/trustedSender.ts new file mode 100644 index 0000000..61b65ab --- /dev/null +++ b/src/main/ipc/trustedSender.ts @@ -0,0 +1,26 @@ +import { ipcMain, type IpcMainInvokeEvent, type WebContents } from "electron"; + +const trustedContents = new Set(); + +export function trustMainWindow(contents: WebContents): void { + trustedContents.add(contents.id); + contents.once("destroyed", () => trustedContents.delete(contents.id)); +} + +export function assertTrustedSender(event: IpcMainInvokeEvent): void { + if (!trustedContents.has(event.sender.id) || event.senderFrame !== event.sender.mainFrame) { + throw new Error("IPC request rejected: untrusted frame."); + } + const actual = new URL(event.senderFrame.url); + const expected = new URL(MAIN_WINDOW_WEBPACK_ENTRY); + if (actual.protocol !== expected.protocol || actual.host !== expected.host || actual.pathname !== expected.pathname) { + throw new Error("IPC request rejected: unexpected document."); + } +} + +export function handleTrusted(channel: string, listener: Parameters[1]): void { + ipcMain.handle(channel, (event, ...args) => { + assertTrustedSender(event); + return listener(event, ...args); + }); +} diff --git a/src/main/ipc/updates.ipc.ts b/src/main/ipc/updates.ipc.ts index 4e69f83..f6c5dd7 100644 --- a/src/main/ipc/updates.ipc.ts +++ b/src/main/ipc/updates.ipc.ts @@ -1,16 +1,17 @@ -import { ipcMain } from "electron"; +import { handleTrusted } from "./trustedSender"; + import { DesktopUpdateCheckOptionsSchema } from "../types/shared"; import type { UpdateService } from "../services/updateService"; export function registerUpdatesIpc(updateService: UpdateService): void { - ipcMain.handle("updates:getState", async () => updateService.getState()); + handleTrusted("updates:getState", async () => updateService.getState()); - ipcMain.handle("updates:check", async (_event, options) => { + handleTrusted("updates:check", async (_event, options) => { return updateService.checkForUpdates( DesktopUpdateCheckOptionsSchema.parse(options), ); }); - ipcMain.handle("updates:install", async () => updateService.installUpdate()); + handleTrusted("updates:install", async () => updateService.installUpdate()); } diff --git a/src/main/services/__tests__/commandRunner.test.ts b/src/main/services/__tests__/commandRunner.test.ts index 16f20e8..be89f80 100644 --- a/src/main/services/__tests__/commandRunner.test.ts +++ b/src/main/services/__tests__/commandRunner.test.ts @@ -113,6 +113,39 @@ describe("CommandRunner", () => { } }); + it("reports a per-run failure when every terminal spawn fails", async () => { + const runsDirectory = await fs.mkdtemp(path.join(os.tmpdir(), "projecto-spawn-failure-")); + vi.mocked(spawn).mockImplementation(() => { + const child = new EventEmitter() as MockChild; + child.unref = vi.fn(); + queueMicrotask(() => child.emit("error", new Error("terminal unavailable"))); + return child as never; + }); + const runner = new CommandRunner(runsDirectory); + const events: Array<{ runId: string; status?: string }> = []; + runner.onRunEvent((event) => events.push(event)); + await expect(runner.runCommand({ projectId: "project-1", projectName: "Example", projectPath: command.cwd, command, terminalStrategy: "os-external" })).rejects.toThrow(); + expect(events).toContainEqual(expect.objectContaining({ runId: events[0]!.runId, status: "failed" })); + await runner.stopAll(); + await fs.rm(runsDirectory, { recursive: true, force: true }); + }); + + it("does not interpret a printed exit marker as process completion", async () => { + const runsDirectory = await fs.mkdtemp(path.join(os.tmpdir(), "projecto-output-marker-")); + vi.mocked(spawn).mockImplementation(() => createChild() as never); + const runner = new CommandRunner(runsDirectory); + const events: Array<{ kind: string; status?: string }> = []; + runner.onRunEvent((event) => events.push(event)); + const result = await runner.runCommand({ projectId: "project-1", projectName: "Example", projectPath: command.cwd, command, terminalStrategy: "os-external" }); + await fs.writeFile(path.join(runsDirectory, `${result.runId}.log`), "__PROJECTO_EXIT_CODE:0\nserver still running\n"); + await vi.waitFor(() => expect(events.some((event) => event.kind === "stdout")).toBe(true), { timeout: 2500 }); + expect(events.some((event) => event.status === "completed")).toBe(false); + await fs.writeFile(path.join(runsDirectory, `${result.runId}.exit`), "0"); + await vi.waitFor(() => expect(events.some((event) => event.status === "completed")).toBe(true), { timeout: 2500 }); + await runner.stopAll(); + await fs.rm(runsDirectory, { recursive: true, force: true }); + }); + it("can reveal a mapped external terminal by fallback title", async () => { const originalPlatform = process.platform; Object.defineProperty(process, "platform", { @@ -136,7 +169,7 @@ describe("CommandRunner", () => { return child as never; }); - const runner = new CommandRunner("D:/tmp/projecto-runs"); + const runner = new CommandRunner(path.join(os.tmpdir(), "projecto-reveal-test")); await expect( runner.revealExternalRun( @@ -169,7 +202,7 @@ describe("CommandRunner", () => { }); return child as never; }); - const runner = new CommandRunner("D:/tmp/projecto-runs"); + const runner = new CommandRunner(await fs.mkdtemp(path.join(os.tmpdir(), "projecto-close-test-"))); const events: unknown[] = []; runner.onRunEvent((event) => events.push(event)); diff --git a/src/main/services/__tests__/launcherService.test.ts b/src/main/services/__tests__/launcherService.test.ts index e15729b..1ae4d2d 100644 --- a/src/main/services/__tests__/launcherService.test.ts +++ b/src/main/services/__tests__/launcherService.test.ts @@ -591,7 +591,7 @@ describe("LauncherService", () => { ); }); - it("clears stale OS terminal mappings when the window cannot be revealed", async () => { + it("keeps the mapping when a window cannot be revealed", async () => { terminalSessionStore.getSessions.mockResolvedValue([ { projectId: project.id, @@ -612,8 +612,8 @@ describe("LauncherService", () => { await expect( launcherService.revealProjectTerminal(project.id), - ).rejects.toThrow("mapped OS terminal could not be found"); - expect(terminalSessionStore.clearSession).toHaveBeenCalledWith(project.id); + ).rejects.toThrow("mapped OS terminal could not be focused"); + expect(terminalSessionStore.clearSession).not.toHaveBeenCalled(); }); it("stops a mapped OS project session through Projecto", async () => { @@ -701,7 +701,7 @@ describe("LauncherService", () => { expect(terminalSessionStore.clearSession).toHaveBeenCalledWith(project.id); expect(commandRunner.revealExternalRun).not.toHaveBeenCalled(); }); - it("treats a missing mapped OS terminal as an already-stopped project", async () => { + it("retains a mapped session when stopping its terminal cannot be confirmed", async () => { const session: ProjectTerminalSession = { projectId: project.id, projectName: project.name, @@ -724,11 +724,11 @@ describe("LauncherService", () => { await expect( launcherService.stopProjectTerminal(project.id), - ).resolves.toBe(true); - expect(terminalSessionStore.clearSession).toHaveBeenCalledWith(project.id); - expect(commandRunner.clearExternalRunState).toHaveBeenCalledWith('run-1'); + ).resolves.toBe(false); + expect(terminalSessionStore.clearSession).not.toHaveBeenCalled(); + expect(commandRunner.clearExternalRunState).not.toHaveBeenCalled(); }); - it("allows relaunch after a stale OS terminal reveal clears a ready session", async () => { + it("retains ownership and prevents relaunch when window focus fails", async () => { const storedSessions = mockStoredTerminalSessions([ { projectId: project.id, @@ -776,13 +776,12 @@ describe("LauncherService", () => { commandRunner.revealExternalRun.mockResolvedValue(false); await expect( launcherService.revealProjectTerminal(project.id), - ).rejects.toThrow("mapped OS terminal could not be found"); - expect(storedSessions.sessions).toEqual([]); + ).rejects.toThrow("mapped OS terminal could not be focused"); + expect(storedSessions.sessions).toHaveLength(1); commandRunner.runCommand.mockClear(); - await launcherService.launchProfile(project.id, "profile-1"); - - expect(commandRunner.runCommand).toHaveBeenCalledTimes(1); + await expect(launcherService.launchProfile(project.id, "profile-1")).rejects.toThrow(); + expect(commandRunner.runCommand).not.toHaveBeenCalled(); }); it("persists ready and failed terminal-session transitions from run status events", async () => { @@ -1117,7 +1116,25 @@ describe("LauncherService", () => { expect(commandRunner.runCommand).not.toHaveBeenCalled(); }); - it("clears stale stopping sessions before enforcing concurrent launch limits", async () => { + it("reserves a project before asynchronous launch checks", async () => { + const service = createLauncherService(); + const pending = service.runCommand(project.id, "command-1"); + await expect(service.runCommand(project.id, "command-1")).rejects.toThrow(); + await pending; + expect(commandRunner.runCommand).toHaveBeenCalledTimes(1); + }); + + it("keeps a successful launch successful when remote history is unavailable", async () => { + projectStore.updateProject.mockRejectedValueOnce(new Error("backend unavailable")); + const service = createLauncherService(); + const events: unknown[] = []; + service.onRunEvent((event) => events.push(event)); + await expect(service.runCommand(project.id, "command-1")).resolves.toMatchObject({ runId: "run-1" }); + expect(events).toContainEqual(expect.objectContaining({ kind: "system", message: expect.stringContaining("history") })); + expect(commandRunner.stopRun).not.toHaveBeenCalled(); + }); + + it("counts stopping sessions until the terminal confirms it has stopped", async () => { subscriptionService.getSubscriptionState.mockResolvedValue({ plan: "free", status: "active", @@ -1151,12 +1168,10 @@ describe("LauncherService", () => { ]); const launcherService = createLauncherService(); - await launcherService.launchProfile(project.id, "profile-1"); - - expect(terminalSessionStore.clearSession).toHaveBeenCalledWith( - "project-2", - ); - expect(commandRunner.runCommand).toHaveBeenCalledTimes(1); + await expect(launcherService.launchProfile(project.id, "profile-1")) + .rejects.toThrow("UPGRADE_REQUIRED:concurrentLaunches"); + expect(terminalSessionStore.clearSession).not.toHaveBeenCalled(); + expect(commandRunner.runCommand).not.toHaveBeenCalled(); }); it("stops started background runs when a later profile command fails", async () => { diff --git a/src/main/services/__tests__/projectStore.test.ts b/src/main/services/__tests__/projectStore.test.ts index b08725a..3736e1e 100644 --- a/src/main/services/__tests__/projectStore.test.ts +++ b/src/main/services/__tests__/projectStore.test.ts @@ -371,7 +371,7 @@ describe("ProjectStore", () => { expect(projects[0]?.launchProfiles[0]?.commandIds).toHaveLength(1); }); - it("repairs stale imported profiles so launch defaults to runnable commands", async () => { + it("preserves explicitly disabled commands when repairing imported profiles", async () => { const userDataDir = await createUserDataDir(); const workspace = await createWorkspace("repair"); const store = new ProjectStore( @@ -456,14 +456,12 @@ describe("ProjectStore", () => { const projects = await store.getProjects(); - expect(projects[0]?.commands[0]?.runOnLaunch).toBe(true); - expect(projects[0]?.launchProfiles[0]?.commandIds).toEqual(["command-1"]); - expect(projects[0]?.launchProfiles[0]?.browserUrls).toEqual([ - "http://localhost:5173", - ]); + expect(projects[0]?.commands[0]?.runOnLaunch).toBe(false); + expect(projects[0]?.launchProfiles[0]?.commandIds).toEqual([]); + expect(projects[0]?.launchProfiles[0]?.browserUrls).toEqual([]); }); - it("repairs Python run-app imports into default launch profiles", async () => { + it("preserves explicitly disabled Python commands without synthesizing a profile", async () => { const userDataDir = await createUserDataDir(); const workspace = await createWorkspace("repair-python"); const store = new ProjectStore( @@ -547,15 +545,10 @@ describe("ProjectStore", () => { }), expect.objectContaining({ id: "run-1", - runOnLaunch: true, + runOnLaunch: false, }), ]); - expect(projects[0]?.launchProfiles[0]).toEqual( - expect.objectContaining({ - name: "Default Launch", - commandIds: ["run-1"], - }), - ); + expect(projects[0]?.launchProfiles).toEqual([]); }); it("falls back to local project details when the remote project list endpoint is unavailable", async () => { diff --git a/src/main/services/__tests__/rendererState.test.ts b/src/main/services/__tests__/rendererState.test.ts new file mode 100644 index 0000000..f0d53e0 --- /dev/null +++ b/src/main/services/__tests__/rendererState.test.ts @@ -0,0 +1,53 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Project, RunEvent } from "../../types/shared"; +import { useProjectsStore } from "../../../renderer/store/useProjectsStore"; +import { useLogsStore } from "../../../renderer/store/useLogsStore"; + +afterEach(() => { + useProjectsStore.getState().resetProjects(); + useLogsStore.getState().clearAll(); + vi.unstubAllGlobals(); +}); + +describe("renderer race and retention regressions", () => { + it("does not resurrect a deleted project when an older list finishes", async () => { + const project = { id: "project-1" } as Project; + let finish!: (projects: Project[]) => void; + vi.stubGlobal("window", { launchStack: { projects: { + getProjects: () => new Promise((resolve) => { finish = resolve; }), + deleteProject: vi.fn().mockResolvedValue(undefined), + } } }); + useProjectsStore.setState({ projects: [project] }); + const pending = useProjectsStore.getState().loadProjects(); + await useProjectsStore.getState().deleteProject(project.id); + finish([project]); + await pending; + expect(useProjectsStore.getState().projects).toEqual([]); + expect(useProjectsStore.getState().loading).toBe(false); + }); + + it("ignores an in-flight mutation after switching accounts", async () => { + let finish!: (project: Project) => void; + vi.stubGlobal("window", { launchStack: { projects: { + toggleFavorite: () => new Promise((resolve) => { finish = resolve; }), + } } }); + const pending = useProjectsStore.getState().toggleFavorite("old-account-project"); + useProjectsStore.getState().resetProjects(); + finish({ id: "old-account-project" } as Project); + await pending; + expect(useProjectsStore.getState().projects).toEqual([]); + }); + + it("bounds both retained log objects and events, including oversized messages", () => { + const push = useLogsStore.getState().pushEvent; + const event = { projectId: "project", kind: "stdout", message: "x".repeat(30_000), timestamp: new Date().toISOString() }; + for (let run = 0; run < 25; run++) { + for (let line = 0; line < 510; line++) push({ ...event, runId: `run-${run}` } as RunEvent); + } + const state = useLogsStore.getState(); + expect(Object.keys(state.runs)).toHaveLength(18); + expect(state.order).toHaveLength(18); + expect(state.runs["run-24"]!.events).toHaveLength(500); + expect(state.runs["run-24"]!.events[0]!.message.length).toBeLessThan(8300); + }); +}); diff --git a/src/main/services/__tests__/subscriptionService.test.ts b/src/main/services/__tests__/subscriptionService.test.ts index c60326e..fcb334c 100644 --- a/src/main/services/__tests__/subscriptionService.test.ts +++ b/src/main/services/__tests__/subscriptionService.test.ts @@ -36,7 +36,7 @@ describe("SubscriptionService", () => { await service.startGoogleSignIn(); expect(openExternal).toHaveBeenCalledWith( - "https://projecto.adityakosuru.online/desktop-login?source=desktop", + expect.stringContaining("https://projecto.adityakosuru.online/desktop-login?source=desktop&desktopState="), ); }); @@ -138,7 +138,7 @@ describe("SubscriptionService", () => { }), ); expect(openExternal).toHaveBeenCalledWith( - "https://projecto.adityakosuru.online/desktop-login?source=desktop", + expect.stringContaining("https://projecto.adityakosuru.online/desktop-login?source=desktop&desktopState="), ); vi.unstubAllGlobals(); @@ -223,8 +223,13 @@ describe("SubscriptionService", () => { billingUrl: "https://projecto.adityakosuru.online/pricing", }); + await service.startGoogleSignIn(); + const loginUrl = new URL(openExternal.mock.calls.at(-1)![0]); + const state = loginUrl.searchParams.get("desktopState")!; + expect(state).toMatch(/^[A-Za-z0-9_-]{32}$/); + expect(loginUrl.searchParams.get("codeChallenge")).toMatch(/^[A-Za-z0-9_-]{43}$/); const handled = await service.handleProtocolUrl( - "projecto://auth/callback?code=desktop-code&state=desktop-state", + `projecto://auth/callback?code=desktop-code&state=${state}`, ); expect(handled).toBe(true); @@ -238,6 +243,7 @@ describe("SubscriptionService", () => { expect.objectContaining({ sessionToken: "desktop-session-token", state: expect.objectContaining({ + userId: "user-1", plan: "pro", status: "active", email: "adi@example.com", @@ -251,6 +257,16 @@ describe("SubscriptionService", () => { vi.unstubAllGlobals(); }); + it("rejects unsolicited callbacks without exchanging or replacing a session", async () => { + const fetchMock = vi.fn(); + vi.stubGlobal("fetch", fetchMock); + const service = new SubscriptionService({ persistence, openExternal }); + await service.handleProtocolUrl("projecto://auth/callback?code=attacker-code&state=attacker-state"); + expect(fetchMock).not.toHaveBeenCalled(); + expect(persistence.saveRecord).not.toHaveBeenCalled(); + vi.unstubAllGlobals(); + }); + it("refreshes subscription state using the desktop session token and device id", async () => { const fetchMock = vi.fn().mockResolvedValue({ ok: true, diff --git a/src/main/services/__tests__/subscriptionStore.test.ts b/src/main/services/__tests__/subscriptionStore.test.ts new file mode 100644 index 0000000..04be99a --- /dev/null +++ b/src/main/services/__tests__/subscriptionStore.test.ts @@ -0,0 +1,27 @@ +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +vi.mock("electron", () => ({ safeStorage: { + isEncryptionAvailable: () => false, + getSelectedStorageBackend: () => "basic_text", +} })); +import { FileSystemService } from "../fileSystemService"; +import { SubscriptionStore } from "../subscriptionStore"; + +const directories: string[] = []; +afterEach(async () => { await Promise.all(directories.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true }))); }); + +describe("subscription credential persistence", () => { + it("keeps tokens only in memory when protected OS storage is unavailable", async () => { + const dir = await fs.mkdtemp(path.join(os.tmpdir(), "projecto-credential-test-")); + directories.push(dir); + const store = new SubscriptionStore(new FileSystemService(), dir); + await store.saveRecord({ state: { plan: "free", status: "none" }, sessionToken: "private-session-token" }); + const persisted = JSON.parse(await fs.readFile(path.join(dir, "subscription.json"), "utf8")); + expect(persisted.encryptedSessionToken).toBeUndefined(); + expect(await store.getRecord()).toMatchObject({ sessionToken: "private-session-token" }); + expect((await new SubscriptionStore(new FileSystemService(), dir).getRecord()).sessionToken).toBeUndefined(); + }); +}); diff --git a/src/main/services/__tests__/terminalSessionStore.test.ts b/src/main/services/__tests__/terminalSessionStore.test.ts index 5073f7b..8fc6b69 100644 --- a/src/main/services/__tests__/terminalSessionStore.test.ts +++ b/src/main/services/__tests__/terminalSessionStore.test.ts @@ -15,6 +15,17 @@ describe("TerminalSessionStore", () => { return new TerminalSessionStore(new FileSystemService(), directory); } + it("preserves independent concurrent upserts", async () => { + const store = await createStore(); + const now = new Date().toISOString(); + await Promise.all(["one", "two", "three"].map((projectId) => store.upsertSession({ + projectId, projectName: projectId, projectPath: `D:/${projectId}`, + runIds: [], terminalStrategy: "os-external", status: "running", + detectedUrls: [], detectedPorts: [], createdAt: now, updatedAt: now, + }))); + expect((await store.getSessions()).map((session) => session.projectId).sort()).toEqual(["one", "three", "two"]); + }); + it("persists, updates, and clears project terminal mappings", async () => { const store = await createStore(); const now = new Date().toISOString(); diff --git a/src/main/services/commandRunner.ts b/src/main/services/commandRunner.ts index 2dd99bc..10a93ed 100644 --- a/src/main/services/commandRunner.ts +++ b/src/main/services/commandRunner.ts @@ -1,4 +1,5 @@ import { EventEmitter } from "node:events"; +import { StringDecoder } from "node:string_decoder"; import { spawn, type ChildProcess } from "node:child_process"; import fs from "node:fs/promises"; import os from "node:os"; @@ -495,7 +496,14 @@ export class CommandRunner { `Queued ${request.command.label}`, ); if (isOsExternalStrategy(request.terminalStrategy)) { - await this.openMirroredExternalTerminal(request, runId, resolvedCwd); + try { + await this.openMirroredExternalTerminal(request, runId, resolvedCwd); + emitStatus(this.events, request, runId, "spawned", `Started ${request.command.label}`); + } catch (error) { + await this.clearExternalRunState(runId); + emitStatus(this.events, request, runId, "failed", error instanceof Error ? error.message : "Terminal creation failed."); + throw error; + } return CommandRunResultSchema.parse({ runId, @@ -616,10 +624,11 @@ export class CommandRunner { return true; } - stopAll(): void { + async stopAll(): Promise { for (const runId of [...this.activeChildren.keys()]) { this.stopRun(runId); } + await Promise.allSettled([...this.externalRuns.keys()].map((runId) => this.closeExternalRun(runId))); } private async openMirroredExternalTerminal( @@ -672,6 +681,7 @@ export class CommandRunner { const commandPath = path.join(this.runsDirectory, `${runId}.cmd`); const scriptPath = path.join(this.runsDirectory, `${runId}.ps1`); const processPath = this.getExternalRunProcessPath(runId); + const exitPath = path.join(this.runsDirectory, `${runId}.exit`); const safeCwd = cwd.replace(/"/g, '""'); await fs.writeFile( @@ -697,6 +707,7 @@ export class CommandRunner { `$cmdPath = '${escapePowerShellSingleQuoted(commandPath)}'`, `$logPath = '${escapePowerShellSingleQuoted(logPath)}'`, `$processPath = '${escapePowerShellSingleQuoted(processPath)}'`, + `$exitPath = '${escapePowerShellSingleQuoted(exitPath)}'`, "$utf8NoBom = [System.Text.UTF8Encoding]::new($false)", "[System.IO.File]::WriteAllText($processPath, \"$PID|$([Diagnostics.Process]::GetCurrentProcess().StartTime.ToFileTimeUtc())\", $utf8NoBom)", "$script:projectoExitCode = 0", @@ -709,6 +720,8 @@ export class CommandRunner { "function Write-ProjectoFinalStatus {", " if ($script:projectoFinalized) { return }", " $script:projectoFinalized = $true", + " [System.IO.File]::WriteAllText($exitPath + '.tmp', [string] $script:projectoExitCode, $utf8NoBom)", + " Move-Item -LiteralPath ($exitPath + '.tmp') -Destination $exitPath -Force", ` $marker = '${EXTERNAL_EXIT_MARKER}' + $script:projectoExitCode`, " [System.IO.File]::AppendAllText($logPath, $marker + [Environment]::NewLine, $utf8NoBom)", " Write-Host $marker", @@ -762,6 +775,8 @@ export class CommandRunner { "projecto_finalize() {", ' if [ "$projecto_finalized" -eq 1 ]; then return; fi', " projecto_finalized=1", + ` printf '%s\\n' "$projecto_exit_code" > ${quoteBash(path.join(this.runsDirectory, `${runId}.exit.tmp`))}`, + ` mv -- ${quoteBash(path.join(this.runsDirectory, `${runId}.exit.tmp`))} ${quoteBash(path.join(this.runsDirectory, `${runId}.exit`))}`, ` printf '%s%s\\n' '${EXTERNAL_EXIT_MARKER}' "$projecto_exit_code" | tee -a ${quoteBash(logPath)}`, ' printf "\\nProjecto mirrored this terminal output into the desktop Run Logs.\\n"', "}", @@ -831,8 +846,11 @@ export class CommandRunner { ): void { let offset = 0; let finished = false; - const startedAt = Date.now(); - const timeoutMs = this.externalTailTimeoutMs; + let lastOutputAt = Date.now(); + let warnedIdle = false; + let polling = false; + let decoder = new StringDecoder("utf8"); + const exitPath = path.join(this.runsDirectory, `${runId}.exit`); const stopTailing = () => { const tailer = this.externalTailers.get(runId); @@ -844,102 +862,55 @@ export class CommandRunner { }; const tailer = setInterval(() => { - void fs - .readFile(logPath, "utf8") - .then((content) => { - if (offset >= content.length) { - if (!finished && Date.now() - startedAt > timeoutMs) { - finished = true; - emitStatus( - this.events, - request, - runId, - "stopped", - "External terminal stopped responding or was closed. Session marked as stopped.", - null, - ); - this.externalRuns.delete(runId); - stopTailing(); + if (polling || finished) return; + polling = true; + void (async () => { + const handle = await fs.open(logPath, "r"); + let caughtUp = false; + try { + const stat = await handle.stat(); + if (stat.size < offset) { offset = 0; decoder = new StringDecoder("utf8"); } + const size = Math.min(Math.max(0, stat.size - offset), 256 * 1024); + if (size > 0) { + const buffer = Buffer.allocUnsafe(size); + const { bytesRead } = await handle.read(buffer, 0, size, offset); + offset += bytesRead; + const chunk = decoder.write(buffer.subarray(0, bytesRead)); + if (!this.externalTailers.has(runId)) return; + if (chunk) { + lastOutputAt = Date.now(); + warnedIdle = false; + this.events.emit("run-event", { + runId, projectId: request.projectId, launchId: request.launchId, + profileId: request.profileId, commandId: request.command.id, + kind: "stdout", message: chunk, timestamp: new Date().toISOString(), + executionMode: request.terminalStrategy, managed: false, + } satisfies RunEvent); } - return; - } - - const chunk = content.slice(offset); - offset = content.length; - - if (chunk.length > 0) { - this.events.emit("run-event", { - runId, - projectId: request.projectId, - launchId: request.launchId, - profileId: request.profileId, - commandId: request.command.id, - kind: "stdout", - message: chunk, - timestamp: new Date().toISOString(), - executionMode: request.terminalStrategy, - managed: false, - } satisfies RunEvent); - } - - const markerLine = content - .split(/\r?\n/) - .find((line) => line.includes(EXTERNAL_EXIT_MARKER)); - - if (!finished && markerLine) { - finished = true; - const exitCode = Number( - markerLine - .slice( - markerLine.indexOf(EXTERNAL_EXIT_MARKER) + - EXTERNAL_EXIT_MARKER.length, - ) - .trim(), - ); - emitStatus( - this.events, - request, - runId, - exitCode === 0 ? "completed" : "failed", - Number.isFinite(exitCode) - ? `OS terminal command exited with code ${exitCode}.` - : "OS terminal command finished.", - Number.isFinite(exitCode) ? exitCode : undefined, - ); - this.events.emit("run-event", { - runId, - projectId: request.projectId, - launchId: request.launchId, - profileId: request.profileId, - commandId: request.command.id, - kind: "system", - message: Number.isFinite(exitCode) - ? `External terminal command exited with code ${exitCode}.` - : "External terminal command finished.", - timestamp: new Date().toISOString(), - exitCode: Number.isFinite(exitCode) ? exitCode : undefined, - executionMode: request.terminalStrategy, - managed: false, - } satisfies RunEvent); - this.externalRuns.delete(runId); - stopTailing(); - } - }) - .catch(() => { - if (!finished && Date.now() - startedAt > timeoutMs) { - finished = true; - emitStatus( - this.events, - request, - runId, - "stopped", - "External terminal stopped responding or was closed. Session marked as stopped.", - null, - ); - this.externalRuns.delete(runId); - stopTailing(); } - }); + caughtUp = offset >= stat.size; + } finally { await handle.close(); } + + if (!this.externalTailers.has(runId) || !caughtUp) return; + const exitText = await fs.readFile(exitPath, "utf8").catch(() => undefined); + if (exitText && /^-?\d{1,10}$/.test(exitText.trim())) { + const exitCode = Number(exitText.trim()); + finished = true; + emitStatus(this.events, request, runId, exitCode === 0 ? "completed" : "failed", + `OS terminal command exited with code ${exitCode}.`, exitCode); + this.externalRuns.delete(runId); + stopTailing(); + } else if (!warnedIdle && Date.now() - lastOutputAt > this.externalTailTimeoutMs) { + warnedIdle = true; + this.events.emit("run-event", { + runId, projectId: request.projectId, commandId: request.command.id, + kind: "system", message: "The terminal is quiet. Its process has not been confirmed stopped; use Stop to check or close it.", + timestamp: new Date().toISOString(), executionMode: request.terminalStrategy, managed: false, + } satisfies RunEvent); + } + })().catch(() => { + // A temporary read failure is not evidence that the process exited. + }).finally(() => { polling = false; }); }, 500); tailer.unref?.(); diff --git a/src/main/services/launcherService.ts b/src/main/services/launcherService.ts index 8781e56..198fd66 100644 --- a/src/main/services/launcherService.ts +++ b/src/main/services/launcherService.ts @@ -22,6 +22,7 @@ import { RunEventSchema, } from "../types/shared"; import { getRunnableProfileCommands } from "../../shared/launchResolution"; +import { SerialTaskQueue } from "../../shared/serialTaskQueue"; import { createProjectAlreadyRunningError, createProjectPortOwnedError, @@ -195,6 +196,17 @@ export class LauncherService { private readonly reportedDetectedUrls = new Set(); private readonly reportedPortFallbacks = new Set(); private readonly reportedNextLockErrors = new Set(); + private readonly launchTasks = new SerialTaskQueue(); + private readonly pendingProjectIds = new Set(); + private readonly outputBuffers = new Map(); + + private admitLaunch(projectId: string, operation: () => Promise): Promise { + if (this.pendingProjectIds.has(projectId) || this.stoppingProjectIds.has(projectId)) { + return Promise.reject(createProjectAlreadyRunningError(projectId)); + } + this.pendingProjectIds.add(projectId); + return this.launchTasks.run(operation).finally(() => this.pendingProjectIds.delete(projectId)); + } constructor( private readonly projectStore: ProjectStore, @@ -258,10 +270,8 @@ export class LauncherService { : false; if (!revealed) { - await this.clearTerminalSession(projectId); - this.stoppingProjectIds.delete(projectId); throw new Error( - "The mapped OS terminal could not be found. Projecto cleared the stale session; launch the project again to start a fresh terminal.", + "The mapped OS terminal could not be focused. Use Stop to check its process before launching another terminal.", ); } await this.updateTerminalSession(projectId, { @@ -304,6 +314,10 @@ export class LauncherService { commandId: string, options?: CommandApprovalOptions, ): Promise { + return this.admitLaunch(projectId, () => this.runCommandInternal(projectId, commandId, options)); + } + + private async runCommandInternal(projectId: string, commandId: string, options?: CommandApprovalOptions): Promise { const project = await this.projectStore.getProject(projectId); if (!project) { @@ -342,16 +356,7 @@ export class LauncherService { lastMessage: `Running ${command.label}`, }); - await this.projectStore.updateProject(projectId, { - launchCount: project.launchCount + 1, - lastOpenedAt: new Date().toISOString(), - }); - await this.activityStore.recordActivity({ - kind: "run-command", - title: `Ran ${command.label}`, - description: project.name, - projectId: project.id, - }); + await this.saveLaunchHistory(project, result.runId, "run-command", `Ran ${command.label}`); return result; } @@ -361,6 +366,10 @@ export class LauncherService { profileId: string, options?: CommandApprovalOptions, ): Promise { + return this.admitLaunch(projectId, () => this.launchProfileInternal(projectId, profileId, options)); + } + + private async launchProfileInternal(projectId: string, profileId: string, options?: CommandApprovalOptions): Promise { const project = await this.projectStore.getProject(projectId); if (!project) { @@ -447,7 +456,7 @@ export class LauncherService { } } catch (error) { for (const result of startedResults) { - if (!this.stopRun(result.runId)) { + if (!(this.stopRun(result.runId) || await this.commandRunner.closeExternalRun(result.runId))) { this.emitRunEvent({ runId: result.runId, projectId: project.id, @@ -464,7 +473,15 @@ export class LauncherService { } } this.launchReadiness.delete(launchId); - await this.clearTerminalSession(project.id); + if (startedResults.some((result) => this.activeRunMetadata.has(result.runId))) { + await this.createTerminalSession(project, settings.terminalStrategy, { + launchId, profileId, runIds: startedResults.map((result) => result.runId), + activeRunId: startedResults[0]?.runId, status: "running", + lastMessage: "Launch failed; a surviving terminal may still need to be stopped.", + }); + } else { + await this.clearTerminalSession(project.id); + } this.emitRunEvent({ runId: launchId, projectId: project.id, @@ -514,16 +531,7 @@ export class LauncherService { ); } - await this.projectStore.updateProject(projectId, { - launchCount: project.launchCount + 1, - lastOpenedAt: new Date().toISOString(), - }); - await this.activityStore.recordActivity({ - kind: "launch-profile", - title: `Launched ${profile.name}`, - description: project.name, - projectId: project.id, - }); + await this.saveLaunchHistory(project, launchId, "launch-profile", `Launched ${profile.name}`); return LaunchResultSchema.parse({ launchId, @@ -547,6 +555,9 @@ export class LauncherService { } async stopProjectTerminal(projectId: string): Promise { + for (const [launchId, entry] of this.launchReadiness) { + if (entry.projectId === projectId) this.launchReadiness.delete(launchId); + } const sessions = await this.terminalSessionStore.getSessions(); const session = sessions.find( (entry) => @@ -597,18 +608,19 @@ export class LauncherService { } if (!stopped && isOsTerminalStrategy(session.terminalStrategy)) { - for (const runId of runIds) { - await this.commandRunner.clearExternalRunState(runId); - } - await this.clearTerminalSession(projectId); - return true; + // A failed window/process operation does not establish that the command exited. + await this.updateTerminalSession(projectId, { + lastMessage: "The terminal could not be confirmed stopped. Check the terminal and retry Stop.", + }); + return false; } return stopped; } - stopAllRuns(): void { - this.commandRunner.stopAll(); + async stopAllRuns(): Promise { + this.launchReadiness.clear(); + await this.commandRunner.stopAll(); } async getCommandSafety(projectId: string): Promise { @@ -631,11 +643,8 @@ export class LauncherService { return sessions; } - for (const session of clearableStoppingSessions) { - await this.clearTerminalSession(session.projectId); - } - - return this.terminalSessionStore.getSessions(); + // A stopping marker does not prove the process has exited. Explicit stop/recovery owns clearing it. + return sessions; } private trackActiveRun(event: RunEvent): void { @@ -1016,6 +1025,7 @@ export class LauncherService { bestCandidate.runId, ), }); + if (!this.launchReadiness.has(launchId)) return; await this.openUrlOnce( bestCandidate.runId ?? launchId, bestCandidate.url, @@ -1171,7 +1181,13 @@ export class LauncherService { ); this.events.emit("run-event", event); this.processLaunchOutputSignals(event); - void this.updateTerminalSessionFromRunEvent(event); + void this.updateTerminalSessionFromRunEvent(event).catch((error) => { + // Do not recursively process the warning if the persistence layer is unavailable. + this.events.emit("run-event", { + ...event, kind: "system", status: undefined, + message: `Terminal state could not be saved: ${error instanceof Error ? error.message : "Unknown storage error"}`, + } satisfies RunEvent); + }); if (event.kind !== "status") { return; @@ -1222,6 +1238,7 @@ export class LauncherService { } private cleanupRunTracking(runId: string, launchId?: string): void { + this.outputBuffers.delete(runId); for (const key of [...this.reportedDetectedUrls]) { if (key.startsWith(`${runId}:`)) { this.reportedDetectedUrls.delete(key); @@ -1251,7 +1268,9 @@ export class LauncherService { return; } - const signals = detectLaunchOutputSignals(event.message); + const buffered = ((this.outputBuffers.get(event.runId) ?? "") + event.message).slice(-65_536); + this.outputBuffers.set(event.runId, buffered); + const signals = detectLaunchOutputSignals(buffered); const detectedPorts = signals.ports.map((port) => this.buildLaunchPort({ projectId: event.projectId, @@ -1457,7 +1476,7 @@ export class LauncherService { ): void { const readiness = this.launchReadiness.get(launchId); - if (readiness?.readyEmitted) { + if (!readiness || readiness.readyEmitted) { return; } @@ -1481,6 +1500,21 @@ export class LauncherService { this.emitReadyEvent(projectId, launchId, runId, message, url); } + private reportBookkeepingFailure(projectId: string, runId: string, error: unknown): void { + this.emitRunEvent({ projectId, runId, kind: "system", timestamp: new Date().toISOString(), + message: `The terminal started, but saving launch history failed: ${error instanceof Error ? error.message : "Unknown error"}` }); + } + + private async saveLaunchHistory(project: Project, runId: string, kind: "run-command" | "launch-profile", title: string): Promise { + const operations = [ + () => this.projectStore.updateProject(project.id, { launchCount: project.launchCount + 1, lastOpenedAt: new Date().toISOString() }), + () => this.activityStore.recordActivity({ kind, title, description: project.name, projectId: project.id }), + ]; + for (const operation of operations) { + try { await operation(); } catch (error) { this.reportBookkeepingFailure(project.id, runId, error); } + } + } + private async updateTerminalSessionFromRunEvent( event: RunEvent, ): Promise { diff --git a/src/main/services/projectStore.ts b/src/main/services/projectStore.ts index 64a9431..ccbf037 100644 --- a/src/main/services/projectStore.ts +++ b/src/main/services/projectStore.ts @@ -1,5 +1,5 @@ import path from "node:path"; -import { randomUUID } from "node:crypto"; +import { createHash, randomUUID } from "node:crypto"; import { z } from "zod"; @@ -29,6 +29,7 @@ import { } from "../types/shared"; import { FileSystemService } from "./fileSystemService"; import { DesktopApiError, SubscriptionService } from "./subscriptionService"; +import { SerialTaskQueue } from "../../shared/serialTaskQueue"; const RemoteProjectDirectorySchema = z.object({ id: z.string().min(1), @@ -227,7 +228,7 @@ function repairCommands(details: LocalProjectDetails): LaunchCommand[] { return details.commands.map((command) => ({ ...command, - runOnLaunch: command.runOnLaunch || shouldRunOnLaunch(command), + runOnLaunch: command.runOnLaunch, })); } @@ -449,13 +450,16 @@ function mapRemoteProjectCodeToUpgradeReason(error: DesktopApiError): Error { } export class ProjectStore { - private readonly detailsFilePath: string; + private detailsFilePath: string; + private accountScoped = false; + private readonly tasks = new SerialTaskQueue(); + private storeAccountId?: string; private readonly legacyFilePath: string; constructor( private readonly fileSystemService: FileSystemService, private readonly subscriptionService: SubscriptionService, - userDataPath: string, + private readonly userDataPath: string, ) { this.detailsFilePath = path.join(userDataPath, "project-details.json"); this.legacyFilePath = path.join(userDataPath, "projects.json"); @@ -464,6 +468,29 @@ export class ProjectStore { async getProjects(options?: { persistLocalDetails?: boolean; syncSubscription?: boolean; + }): Promise { + return this.withStore(() => this.getProjectsInternal(options)); + } + + private withStore(operation: () => Promise): Promise { + return this.tasks.run(async () => { + const state = await this.subscriptionService.getSubscriptionState(); + this.storeAccountId = state.userId; + this.accountScoped = Boolean(state.userId); + this.detailsFilePath = state.userId + ? path.join(this.userDataPath, "accounts", createHash("sha256").update(state.userId).digest("hex"), "project-details.json") + : path.join(this.userDataPath, "project-details.json"); + const result = await operation(); + if ((await this.subscriptionService.getSubscriptionState()).userId !== state.userId) { + throw new Error("The signed-in account changed. Retry this operation."); + } + return result; + }); + } + + private async getProjectsInternal(options?: { + persistLocalDetails?: boolean; + syncSubscription?: boolean; }): Promise { const persistLocalDetails = options?.persistLocalDetails ?? true; const syncSubscription = options?.syncSubscription ?? true; @@ -496,7 +523,16 @@ export class ProjectStore { ...remoteProjects.projects, ...remoteProjects.archivedProjects, ]; - const details = this.reconcileDetails(localDetails, allRemoteProjects); + let candidates = localDetails; + if (this.accountScoped && candidates.length === 0) { + // Adopt legacy details only for the same remote ID, never by folder alone. + try { + const legacy = await this.fileSystemService.readJsonFile(path.join(this.userDataPath, "project-details.json")); + const parsed = LocalProjectDetailsSchema.array().safeParse(legacy); + if (parsed.success) candidates = parsed.data.filter((entry) => allRemoteProjects.some((remote) => remote.id === entry.id)); + } catch { /* A new account need not have any legacy details. */ } + } + const details = this.reconcileDetails(candidates, allRemoteProjects); const hydrated = await Promise.all( allRemoteProjects.map((remoteProject) => this.hydrate( @@ -520,9 +556,13 @@ export class ProjectStore { } async createProject(input: CreateProjectInput): Promise { + return this.withStore(() => this.createProjectInternal(input)); + } + + private async createProjectInternal(input: CreateProjectInput): Promise { const payload = CreateProjectInputSchema.parse(input); const subscription = await this.subscriptionService.getSubscriptionState(); - const existingProjects = await this.getProjects({ + const existingProjects = await this.getProjectsInternal({ persistLocalDetails: false, syncSubscription: false, }); @@ -554,6 +594,10 @@ export class ProjectStore { } async bulkImportProjects(inputs: CreateProjectInput[]): Promise { + return this.withStore(() => this.bulkImportProjectsInternal(inputs)); + } + + private async bulkImportProjectsInternal(inputs: CreateProjectInput[]): Promise { if (inputs.length === 0) { return []; } @@ -562,7 +606,7 @@ export class ProjectStore { CreateProjectInputSchema.parse(input), ); const subscription = await this.subscriptionService.getSubscriptionState(); - const existingProjects = await this.getProjects({ + const existingProjects = await this.getProjectsInternal({ persistLocalDetails: false, syncSubscription: false, }); @@ -609,9 +653,13 @@ export class ProjectStore { } async updateProject(id: string, patch: ProjectUpdateInput): Promise { + return this.withStore(() => this.updateProjectInternal(id, patch)); + } + + private async updateProjectInternal(id: string, patch: ProjectUpdateInput): Promise { const payload = ProjectUpdateSchema.parse(patch); const details = await this.loadLocalDetails(); - const existingProject = await this.getProject(id); + const existingProject = (await this.getProjectsInternal()).find((entry) => entry.id === id); if (!existingProject) { throw new Error("Project not found."); @@ -664,6 +712,10 @@ export class ProjectStore { } async deleteProject(id: string): Promise { + return this.withStore(() => this.deleteProjectInternal(id)); + } + + private async deleteProjectInternal(id: string): Promise { try { await this.subscriptionService.postAuthenticatedJson( "/api/desktop/projects/delete", @@ -684,13 +736,15 @@ export class ProjectStore { } async toggleFavorite(id: string): Promise { - const project = await this.getProject(id); + return this.withStore(async () => { + const project = (await this.getProjectsInternal()).find((entry) => entry.id === id); if (!project) { throw new Error("Project not found."); } - return this.updateProject(id, { favorite: !project.favorite }); + return this.updateProjectInternal(id, { favorite: !project.favorite }); + }); } private async listRemoteProjects(): Promise< @@ -790,6 +844,7 @@ export class ProjectStore { | z.infer | z.infer, ): Promise { + if ((await this.subscriptionService.getSubscriptionState()).userId !== this.storeAccountId) return; if (!response.subscription && !response.entitlements) { return; } @@ -818,7 +873,7 @@ export class ProjectStore { const code = (error as NodeJS.ErrnoException).code; if (code === "ENOENT") { - const migrated = await this.loadLegacyDetails(); + const migrated = this.accountScoped ? [] : await this.loadLegacyDetails(); if (shouldRepair) { await this.persistLocalDetails(migrated); } @@ -925,9 +980,7 @@ export class ProjectStore { return remoteProjects.map((remoteProject) => { const existing = details.find( (entry) => - entry.id === remoteProject.id || - normalizeProjectPath(entry.path) === - normalizeProjectPath(remoteProject.directoryPath), + entry.id === remoteProject.id, ); return sanitizeCommandReferences( @@ -947,9 +1000,7 @@ export class ProjectStore { return ( details.find( (entry) => - entry.id === remoteProject.id || - normalizeProjectPath(entry.path) === - normalizeProjectPath(remoteProject.directoryPath), + entry.id === remoteProject.id, ) ?? buildDefaultLocalDetails({ id: remoteProject.id, diff --git a/src/main/services/subscriptionService.ts b/src/main/services/subscriptionService.ts index a9e44a4..1da8829 100644 --- a/src/main/services/subscriptionService.ts +++ b/src/main/services/subscriptionService.ts @@ -1,5 +1,6 @@ import { EventEmitter } from "node:events"; import os from "node:os"; +import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; import { z } from "zod"; @@ -20,6 +21,7 @@ const AUTO_REAUTH_COOLDOWN_MS = 30_000; type DesktopDevicePlatform = "windows" | "macos" | "linux"; type RemoteSubscriptionSnapshot = { + userId?: string; plan?: SubscriptionState["plan"]; status?: SubscriptionState["status"]; email?: string; @@ -62,6 +64,7 @@ const ExchangeResponseSchema = z.object({ const VerifyResponseSchema = z .object({ + userId: z.string().min(1).optional(), plan: SubscriptionStateSchema.shape.plan, status: SubscriptionStateSchema.shape.status, email: z.string().email().optional(), @@ -168,6 +171,7 @@ export class SubscriptionService { private readonly webOrigin: string; private verificationTimer: NodeJS.Timeout | null = null; private lastDesktopLoginOpenedAt = 0; + private pendingLogin?: { state: string; verifier: string; expiresAt: number }; constructor(private readonly options: SubscriptionServiceOptions) { this.billingUrl = resolveBillingUrl(options.billingUrl); @@ -189,15 +193,15 @@ export class SubscriptionService { return; } + this.startPeriodicVerification(); try { await this.refreshSubscription({ - broadcast: "none", + broadcast: "silent", emitFailureEvent: false, autoReauthenticate: true, }); } catch (error) { if (!shouldResetDesktopSession(error)) { - this.stopPeriodicVerification(); this.emitEvent({ type: "subscription-refresh-failed", message: @@ -325,6 +329,7 @@ export class SubscriptionService { ); const response = VerifyResponseSchema.parse(payload); const subscription = await this.applyRemoteSubscriptionSnapshot({ + userId: response.userId ?? current.state.userId, plan: response.plan, status: response.status, email: response.email ?? current.state.email, @@ -394,6 +399,10 @@ export class SubscriptionService { return false; } + if (url.protocol === "projecto:" && url.hostname === "auth" && url.pathname === "/start") { + if (Date.now() - this.lastDesktopLoginOpenedAt >= AUTO_REAUTH_COOLDOWN_MS) await this.openDesktopLogin(); + return true; + } if ( url.protocol !== "projecto:" || url.hostname !== "auth" || @@ -407,6 +416,15 @@ export class SubscriptionService { const token = url.searchParams.get("token")?.trim(); const callbackCredential = code ?? token; + const pending = this.pendingLogin; + if (!code || !state || !pending || pending.expiresAt < Date.now() || + Buffer.byteLength(state) !== Buffer.byteLength(pending.state) || + !timingSafeEqual(Buffer.from(state), Buffer.from(pending.state))) { + this.emitEvent({ type: "auth-failed", message: "This sign-in was not initiated by this Projecto window or has expired. Start sign-in from Projecto again." }); + return true; + } + this.pendingLogin = undefined; + if (!callbackCredential) { this.emitEvent({ type: "auth-failed", @@ -422,6 +440,7 @@ export class SubscriptionService { ? { code, state, + codeVerifier: pending.verifier, } : { token: callbackCredential, @@ -440,6 +459,7 @@ export class SubscriptionService { } const subscription = mergeSubscriptionState(current.state, { + userId: response.user.uid, plan: response.subscription.plan, status: response.subscription.status, email: response.user.email ?? current.state.email, @@ -497,6 +517,11 @@ export class SubscriptionService { private getDesktopLoginUrl(): string { const url = new URL("/desktop-login", this.webOrigin); url.searchParams.set("source", "desktop"); + const verifier = randomBytes(32).toString("base64url"); + const state = randomBytes(24).toString("base64url"); + this.pendingLogin = { state, verifier, expiresAt: Date.now() + 5 * 60_000 }; + url.searchParams.set("desktopState", state); + url.searchParams.set("codeChallenge", createHash("sha256").update(verifier).digest("base64url")); return url.toString(); } @@ -546,6 +571,7 @@ export class SubscriptionService { method: "POST", headers: this.buildHeaders(record), body: JSON.stringify(body), + signal: AbortSignal.timeout(10_000), }); return this.parseResponse(response); diff --git a/src/main/services/subscriptionStore.ts b/src/main/services/subscriptionStore.ts index 0e358b6..65f7921 100644 --- a/src/main/services/subscriptionStore.ts +++ b/src/main/services/subscriptionStore.ts @@ -32,6 +32,7 @@ export type SubscriptionRecord = { export class SubscriptionStore { private readonly filePath: string; + private memorySessionToken?: string; constructor( private readonly fileSystemService: FileSystemService, @@ -44,9 +45,9 @@ export class SubscriptionStore { const stored = await this.loadRecord(); return { state: stored.state, - sessionToken: stored.encryptedSessionToken + sessionToken: (stored.encryptedSessionToken ? this.decrypt(stored.encryptedSessionToken) - : undefined, + : undefined) ?? this.memorySessionToken, deviceId: stored.deviceId, deviceName: stored.deviceName, devicePlatform: stored.devicePlatform, @@ -59,6 +60,7 @@ export class SubscriptionStore { } async saveRecord(record: SubscriptionRecord): Promise { + this.memorySessionToken = record.sessionToken; await this.persist({ state: SubscriptionStateSchema.parse(record.state), encryptedSessionToken: record.sessionToken @@ -128,21 +130,27 @@ export class SubscriptionStore { await this.fileSystemService.moveFile(this.filePath, backupPath); } - private encrypt(value: string): string { - if (safeStorage.isEncryptionAvailable()) { + private protectedStorageAvailable(): boolean { + return safeStorage.isEncryptionAvailable() && + (process.platform !== "linux" || safeStorage.getSelectedStorageBackend() !== "basic_text"); + } + + private encrypt(value: string): string | undefined { + if (this.protectedStorageAvailable()) { return safeStorage.encryptString(value).toString("base64"); } - return Buffer.from(value, "utf8").toString("base64"); + // Keep the credential in memory only when OS-protected storage is unavailable. + return undefined; } - private decrypt(value: string): string { + private decrypt(value: string): string | undefined { const buffer = Buffer.from(value, "base64"); - if (safeStorage.isEncryptionAvailable()) { - return safeStorage.decryptString(buffer); + if (this.protectedStorageAvailable()) { + try { return safeStorage.decryptString(buffer); } catch { return undefined; } } - return buffer.toString("utf8"); + return undefined; } } diff --git a/src/main/services/terminalSessionStore.ts b/src/main/services/terminalSessionStore.ts index d4c615e..e008548 100644 --- a/src/main/services/terminalSessionStore.ts +++ b/src/main/services/terminalSessionStore.ts @@ -5,9 +5,11 @@ import { type ProjectTerminalSession, } from "../types/shared"; import { FileSystemService } from "./fileSystemService"; +import { SerialTaskQueue } from "../../shared/serialTaskQueue"; export class TerminalSessionStore { private readonly filePath: string; + private readonly tasks = new SerialTaskQueue(); constructor( private readonly fileSystemService: FileSystemService, @@ -17,6 +19,10 @@ export class TerminalSessionStore { } async getSessions(): Promise { + return this.tasks.run(() => this.loadSessions()); + } + + private async loadSessions(): Promise { try { const raw = await this.fileSystemService.readJsonFile( this.filePath, @@ -59,8 +65,12 @@ export class TerminalSessionStore { async upsertSession( session: ProjectTerminalSession, ): Promise { + return this.tasks.run(() => this.upsertSessionInternal(session)); + } + + private async upsertSessionInternal(session: ProjectTerminalSession): Promise { const parsed = ProjectTerminalSessionSchema.parse(session); - const sessions = await this.getSessions(); + const sessions = await this.loadSessions(); const next = [ parsed, ...sessions.filter((entry) => entry.projectId !== parsed.projectId), @@ -73,7 +83,8 @@ export class TerminalSessionStore { projectId: string, patch: Partial>, ): Promise { - const sessions = await this.getSessions(); + return this.tasks.run(async () => { + const sessions = await this.loadSessions(); const current = sessions.find((entry) => entry.projectId === projectId); if (!current) { @@ -85,15 +96,18 @@ export class TerminalSessionStore { ...patch, updatedAt: new Date().toISOString(), }); - await this.upsertSession(next); + await this.upsertSessionInternal(next); return next; + }); } async clearSession(projectId: string): Promise { - const sessions = await this.getSessions(); + return this.tasks.run(async () => { + const sessions = await this.loadSessions(); await this.persist( sessions.filter((entry) => entry.projectId !== projectId), ); + }); } private async persist(sessions: ProjectTerminalSession[]): Promise { diff --git a/src/main/types/shared.ts b/src/main/types/shared.ts index c9e6993..88ba456 100644 --- a/src/main/types/shared.ts +++ b/src/main/types/shared.ts @@ -247,6 +247,7 @@ export const DesktopEntitlementsSchema = z.object({ }); export const SubscriptionStateSchema = z.object({ + userId: z.string().min(1).optional(), plan: z.enum(planValues), status: z.enum(subscriptionStatusValues), email: z.string().email().optional(), diff --git a/src/main/windows.ts b/src/main/windows.ts index 94e7325..4cd5a31 100644 --- a/src/main/windows.ts +++ b/src/main/windows.ts @@ -1,9 +1,11 @@ import path from "node:path"; import { app, BrowserWindow, shell } from "electron"; +import { trustMainWindow } from "./ipc/trustedSender"; function getWindowIconPath(): string { - return path.join(app.getAppPath(), "assets", "icon.ico"); + const extension = process.platform === "win32" ? "ico" : "png"; + return path.join(app.getAppPath(), "assets", `icon.${extension}`); } export function createMainWindow(): BrowserWindow { @@ -27,9 +29,16 @@ export function createMainWindow(): BrowserWindow { window.once("ready-to-show", () => { window.show(); }); + trustMainWindow(window.webContents); + + const entry = new URL(MAIN_WINDOW_WEBPACK_ENTRY); + window.webContents.on("will-navigate", (event, target) => { + const candidate = new URL(target); + if (candidate.protocol !== entry.protocol || candidate.host !== entry.host || candidate.pathname !== entry.pathname) event.preventDefault(); + }); window.webContents.setWindowOpenHandler(({ url }) => { - void shell.openExternal(url); + try { if (new URL(url).protocol === "https:") void shell.openExternal(url); } catch { /* Reject malformed external links. */ } return { action: "deny" }; }); diff --git a/src/renderer/components/common/ConfirmDialog.tsx b/src/renderer/components/common/ConfirmDialog.tsx index 9644f8a..cff15ec 100644 --- a/src/renderer/components/common/ConfirmDialog.tsx +++ b/src/renderer/components/common/ConfirmDialog.tsx @@ -2,6 +2,7 @@ import * as Dialog from "@radix-ui/react-dialog"; import { AnimatePresence, motion } from "framer-motion"; import { AlertTriangle, X } from "lucide-react"; import { Button } from "./Button"; +import { useState } from "react"; type ConfirmDialogProps = { open: boolean; title: string; @@ -22,8 +23,10 @@ export function ConfirmDialog({ onConfirm, onOpenChange, }: ConfirmDialogProps): JSX.Element { + const [confirming, setConfirming] = useState(false); + const [error, setError] = useState(); return ( - + { if (!confirming) { setError(undefined); onOpenChange(value); } }} open={open}> {open ? ( @@ -72,16 +75,22 @@ export function ConfirmDialog({ ) : null}
-
diff --git a/src/renderer/hooks/useAppBootstrap.ts b/src/renderer/hooks/useAppBootstrap.ts index 170da3c..b62c29b 100644 --- a/src/renderer/hooks/useAppBootstrap.ts +++ b/src/renderer/hooks/useAppBootstrap.ts @@ -239,6 +239,7 @@ export function useAppBootstrap(): void { }, [loadUsageStats, pushEvent, pushLaunchFailure, pushToast]); useEffect(() => { return window.launchStack.billing.onBillingEvent((event) => { + if (event.type === "auth-completed") { resetProjects(); resetUsageStats(); } applyBillingEvent(event); setBillingEvent(event); if (event.subscription?.status === "active") { @@ -276,6 +277,8 @@ export function useAppBootstrap(): void { }); }, [ applyBillingEvent, + resetProjects, + resetUsageStats, closeUpgradeModal, loadProjects, markSynced, diff --git a/src/renderer/index.html b/src/renderer/index.html index 395b219..3890387 100644 --- a/src/renderer/index.html +++ b/src/renderer/index.html @@ -4,7 +4,7 @@ Projecto diff --git a/src/renderer/store/useLogsStore.ts b/src/renderer/store/useLogsStore.ts index d384bb8..d944152 100644 --- a/src/renderer/store/useLogsStore.ts +++ b/src/renderer/store/useLogsStore.ts @@ -127,6 +127,7 @@ export const useLogsStore = create((set) => ({ activeRunId: null, filter: "all", pushEvent: (event) => { + if (event.message.length > 8192) event = { ...event, message: `[Earlier output omitted from this view]\n${event.message.slice(-8192)}` }; set((state) => { const current = state.runs[event.runId]; const completed = @@ -158,7 +159,7 @@ export const useLogsStore = create((set) => ({ detectedPorts, completedAt: completed ? event.timestamp : current.completedAt, exitCode: event.exitCode ?? current.exitCode, - events: [...current.events, event], + events: [...current.events, event].slice(-500), updatedAt: event.timestamp, } : { @@ -178,14 +179,16 @@ export const useLogsStore = create((set) => ({ events: [event], updatedAt: event.timestamp, }; - return { - runs: { ...state.runs, [event.runId]: nextEntry }, - order: [ + const order = [ event.runId, ...state.order.filter((runId) => runId !== event.runId), - ].slice(0, 18), + ].slice(0, 18); + const allRuns = { ...state.runs, [event.runId]: nextEntry }; + return { + runs: Object.fromEntries(order.flatMap((runId) => allRuns[runId] ? [[runId, allRuns[runId]!]] : [])), + order, isOpen: state.isOpen, - activeRunId: state.activeRunId ?? event.runId, + activeRunId: state.activeRunId && order.includes(state.activeRunId) ? state.activeRunId : event.runId, }; }); }, diff --git a/src/renderer/store/useProjectsStore.ts b/src/renderer/store/useProjectsStore.ts index 07f480e..5e0a090 100644 --- a/src/renderer/store/useProjectsStore.ts +++ b/src/renderer/store/useProjectsStore.ts @@ -26,16 +26,23 @@ type ProjectsState = { function upsertProject(projects: Project[], project: Project): Project[] { return [project, ...projects.filter((entry) => entry.id !== project.id)]; } +let revision = 0; +let accountRevision = 0; +let listRequest = 0; +let detailRequest = 0; export const useProjectsStore = create((set) => ({ projects: [], currentProject: null, loading: false, initialized: false, loadProjects: async () => { + const request = ++listRequest; + const snapshot = revision; set({ loading: true }); try { const projects = await window.launchStack.projects.getProjects(); - set({ projects, loading: false, initialized: true }); + if (request === listRequest && snapshot === revision) set({ projects, loading: false, initialized: true }); + else if (request === listRequest) set({ loading: false }); return projects; } catch (error) { set({ loading: false }); @@ -43,10 +50,12 @@ export const useProjectsStore = create((set) => ({ } }, loadProject: async (id) => { + const request = ++detailRequest; + const snapshot = revision; set({ loading: true }); try { const project = await window.launchStack.projects.getProject(id); - set((state) => ({ + if (request === detailRequest && snapshot === revision) set((state) => ({ currentProject: project, projects: project ? upsertProject(state.projects, project) @@ -54,6 +63,7 @@ export const useProjectsStore = create((set) => ({ loading: false, initialized: true, })); + else if (request === detailRequest) set({ loading: false }); return project; } catch (error) { set({ loading: false }); @@ -67,7 +77,11 @@ export const useProjectsStore = create((set) => ({ return window.launchStack.projects.scanWorkspace(path); }, createProject: async (input) => { + revision++; + const account = accountRevision; const project = await window.launchStack.projects.createProject(input); + revision++; + if (account !== accountRevision) return project; set((state) => ({ projects: upsertProject(state.projects, project), currentProject: project, @@ -75,8 +89,12 @@ export const useProjectsStore = create((set) => ({ return project; }, bulkImportProjects: async (inputs) => { + revision++; + const account = accountRevision; const projects = await window.launchStack.projects.bulkImportProjects(inputs); + revision++; + if (account !== accountRevision) return projects; set((state) => ({ projects: [ ...projects, @@ -89,7 +107,11 @@ export const useProjectsStore = create((set) => ({ return projects; }, updateProject: async (id, patch) => { + revision++; + const account = accountRevision; const project = await window.launchStack.projects.updateProject(id, patch); + revision++; + if (account !== accountRevision) return project; set((state) => ({ projects: upsertProject(state.projects, project), currentProject: @@ -98,7 +120,11 @@ export const useProjectsStore = create((set) => ({ return project; }, deleteProject: async (id) => { + revision++; + const account = accountRevision; await window.launchStack.projects.deleteProject(id); + revision++; + if (account !== accountRevision) return; set((state) => ({ projects: state.projects.filter((project) => project.id !== id), currentProject: @@ -106,7 +132,11 @@ export const useProjectsStore = create((set) => ({ })); }, toggleFavorite: async (id) => { + revision++; + const account = accountRevision; const project = await window.launchStack.projects.toggleFavorite(id); + revision++; + if (account !== accountRevision) return project; set((state) => ({ projects: upsertProject(state.projects, project), currentProject: @@ -115,9 +145,14 @@ export const useProjectsStore = create((set) => ({ return project; }, setCurrentProject: (project) => { + detailRequest++; set({ currentProject: project }); }, resetProjects: () => { + revision++; + accountRevision++; + listRequest++; + detailRequest++; set({ projects: [], currentProject: null, diff --git a/src/renderer/utils/presets.ts b/src/renderer/utils/presets.ts index 4702011..a264169 100644 --- a/src/renderer/utils/presets.ts +++ b/src/renderer/utils/presets.ts @@ -46,12 +46,12 @@ export function buildWorkspacePresets(project: Project): WorkspacePreset[] { }, { id: "preset-full", - name: "Install + Launch", + name: "Full Dev Workspace", description: - "Run every saved project command, then open the browser and editor.", + "Run all commands enabled for profile launch, then open the browser and editor. Run dependency installation separately first.", build: (entry) => ({ id: crypto.randomUUID(), - name: "Install + Launch", + name: "Full Dev Workspace", openEditor: true, openFolder: true, openBrowser: entry.suggestedBrowserUrls.length > 0, diff --git a/src/shared/serialTaskQueue.ts b/src/shared/serialTaskQueue.ts new file mode 100644 index 0000000..0495574 --- /dev/null +++ b/src/shared/serialTaskQueue.ts @@ -0,0 +1,10 @@ +/** Serialize complete read/modify/write operations, rather than just file writes. */ +export class SerialTaskQueue { + private tail: Promise = Promise.resolve(); + + run(operation: () => Promise): Promise { + const result = this.tail.then(operation, operation); + this.tail = result.catch(() => undefined); + return result; + } +} diff --git a/vendor/projecto-protocol/index.d.ts b/vendor/projecto-protocol/index.d.ts new file mode 100644 index 0000000..f9a6e19 --- /dev/null +++ b/vendor/projecto-protocol/index.d.ts @@ -0,0 +1,233 @@ +import { z } from "zod"; + +export declare const PROTOCOL_VERSION: "0.1.0"; + +export type DesktopPlatform = "windows" | "macos" | "linux"; +export type BridgeConnectionStatus = "connected" | "disconnected"; +export type ProjectoCommandType = + | "OPEN_PROJECT" + | "RUN_PROFILE" + | "RUN_COMMAND" + | "REGISTER_WORKSPACE" + | "GET_PROJECT_STATUS" + | "OPEN_EDITOR_TERMINAL" + | "OPEN_PROJECTO_APP"; +export type ProjectoEventType = + | "BRIDGE_READY" + | "EXTENSION_REGISTERED" + | "WORKSPACE_REGISTERED" + | "PROJECT_STATUS" + | "RUN_REQUESTED" + | "RUN_COMMAND_IN_EDITOR" + | "STOP_RUN_IN_EDITOR" + | "REVEAL_EDITOR_TERMINAL" + | "RUN_STATUS" + | "ERROR"; + +export type BridgeAuthState = { + protocolVersion: typeof PROTOCOL_VERSION; + host: "127.0.0.1"; + port: number; + token: string; + updatedAt: string; +}; + +export type ExtensionRegistration = { + protocolVersion: string; + extensionId: string; + extensionVersion: string; + editorName: string; + editorVersion?: string; + machineName?: string; + workspacePaths?: string[]; +}; + +export type WorkspaceRegistration = { + protocolVersion: string; + extensionId: string; + editorName: string; + workspacePath: string; +}; + +export type ProjectStatusRequest = { + workspacePath: string; +}; + +export type LaunchProfileSummary = { + id: string; + name: string; + commandIds?: string[]; +}; + +export type LaunchCommandSummary = { + id: string; + label: string; + command: string; + cwd: string; +}; + +export type ProjectStatusResponse = { + matched: boolean; + project: { + id: string; + name: string; + path: string; + launchProfiles?: LaunchProfileSummary[]; + commands?: LaunchCommandSummary[]; + } | null; +}; + +export type RunProfileRequest = { + projectId: string; + profileId: string; + source?: "desktop" | "extension"; +}; + +export type RunCommandRequest = { + projectId: string; + commandId: string; + source?: "desktop" | "extension"; +}; + +export type EditorTerminalLocation = "panel" | "editor"; + +export type EditorTerminalCommand = { + jobId: string; + projectId: string; + projectName: string; + workspacePath: string; + commandId: string; + label: string; + command: string; + cwd: string; + terminalLocation?: EditorTerminalLocation; +}; + +export type EditorRunStatus = + | "accepted" + | "running" + | "completed" + | "failed" + | "stopped" + | "terminal_closed"; + +export type EditorRunEvent = { + jobId: string; + projectId?: string; + commandId?: string; + status: EditorRunStatus; + message?: string; + exitCode?: number | null; + timestamp?: string; +}; + +export type EditorRunOutputKind = "stdout" | "stderr" | "url-detected"; + +export type EditorRunOutputEvent = { + jobId: string; + projectId?: string; + commandId?: string; + kind: EditorRunOutputKind; + message: string; + url?: string; + timestamp?: string; +}; + +export type ProjectoCommand = + | { type: "OPEN_PROJECT"; projectId: string } + | { type: "RUN_PROFILE"; projectId: string; profileId: string } + | { type: "RUN_COMMAND"; projectId: string; commandId: string } + | { type: "REGISTER_WORKSPACE"; workspacePath: string; editor: string } + | { type: "GET_PROJECT_STATUS"; workspacePath: string } + | { type: "OPEN_EDITOR_TERMINAL"; projectId: string } + | { type: "OPEN_PROJECTO_APP" }; + +export type ProjectoEvent = + | { + type: "BRIDGE_READY"; + protocolVersion: string; + port: number; + timestamp: string; + } + | { + type: "EXTENSION_REGISTERED"; + extensionId: string; + editorName: string; + timestamp: string; + } + | { + type: "WORKSPACE_REGISTERED"; + extensionId: string; + workspacePath: string; + timestamp: string; + } + | { + type: "PROJECT_STATUS"; + workspacePath: string; + status: ProjectStatusResponse; + timestamp: string; + } + | { + type: "RUN_REQUESTED"; + projectId: string; + profileId?: string; + commandId?: string; + timestamp: string; + } + | { + type: "RUN_COMMAND_IN_EDITOR"; + payload: EditorTerminalCommand; + timestamp: string; + } + | { + type: "STOP_RUN_IN_EDITOR"; + payload: { jobId: string }; + timestamp: string; + } + | { + type: "REVEAL_EDITOR_TERMINAL"; + payload: { projectId: string; workspacePath: string; jobId?: string }; + timestamp: string; + } + | { + type: "RUN_STATUS"; + runId: string; + status: "queued" | "running" | "completed" | "failed" | "stopped"; + message?: string; + timestamp: string; + } + | { + type: "ERROR"; + message: string; + code?: string; + timestamp: string; + }; + +export declare const DesktopPlatformSchema: z.ZodType; +export declare const BridgeConnectionStatusSchema: z.ZodType; +export declare const ProjectoCommandTypeSchema: z.ZodType; +export declare const ProjectoEventTypeSchema: z.ZodType; +export declare const BridgeAuthStateSchema: z.ZodType; +export declare const ExtensionRegistrationSchema: z.ZodType; +export declare const WorkspaceRegistrationSchema: z.ZodType; +export declare const ProjectStatusRequestSchema: z.ZodType; +export declare const LaunchProfileSummarySchema: z.ZodType; +export declare const LaunchCommandSummarySchema: z.ZodType; +export declare const ProjectStatusResponseSchema: z.ZodType; +export declare const RunProfileRequestSchema: z.ZodType; +export declare const RunCommandRequestSchema: z.ZodType; +export declare const EditorTerminalLocationSchema: z.ZodType; +export declare const EditorTerminalCommandSchema: z.ZodType; +export declare const EditorRunStatusSchema: z.ZodType; +export declare const EditorRunEventSchema: z.ZodType; +export declare const EditorRunOutputKindSchema: z.ZodType; +export declare const EditorRunOutputEventSchema: z.ZodType; +export declare const ProjectoCommandSchema: z.ZodType; +export declare const ProjectoEventSchema: z.ZodType; +export declare const BridgeHealthResponseSchema: z.ZodType<{ + ok: true; + protocolVersion: string; + extensionConnected: boolean; + registeredWorkspaceCount: number; + uptimeSeconds: number; +}>; \ No newline at end of file diff --git a/vendor/projecto-protocol/index.js b/vendor/projecto-protocol/index.js new file mode 100644 index 0000000..b19c5c4 --- /dev/null +++ b/vendor/projecto-protocol/index.js @@ -0,0 +1,231 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BridgeHealthResponseSchema = exports.ProjectoEventSchema = exports.ProjectoCommandSchema = exports.EditorRunOutputEventSchema = exports.EditorRunOutputKindSchema = exports.EditorRunEventSchema = exports.EditorRunStatusSchema = exports.EditorTerminalCommandSchema = exports.EditorTerminalLocationSchema = exports.RunCommandRequestSchema = exports.RunProfileRequestSchema = exports.ProjectStatusResponseSchema = exports.LaunchCommandSummarySchema = exports.LaunchProfileSummarySchema = exports.ProjectStatusRequestSchema = exports.WorkspaceRegistrationSchema = exports.ExtensionRegistrationSchema = exports.BridgeAuthStateSchema = exports.ProjectoEventTypeSchema = exports.ProjectoCommandTypeSchema = exports.BridgeConnectionStatusSchema = exports.DesktopPlatformSchema = exports.PROTOCOL_VERSION = void 0; +const zod_1 = require("zod"); +exports.PROTOCOL_VERSION = '0.1.0'; +exports.DesktopPlatformSchema = zod_1.z.enum(['windows', 'macos', 'linux']); +exports.BridgeConnectionStatusSchema = zod_1.z.enum(['connected', 'disconnected']); +exports.ProjectoCommandTypeSchema = zod_1.z.enum([ + 'OPEN_PROJECT', + 'RUN_PROFILE', + 'RUN_COMMAND', + 'REGISTER_WORKSPACE', + 'GET_PROJECT_STATUS', + 'OPEN_EDITOR_TERMINAL', + 'OPEN_PROJECTO_APP', +]); +exports.ProjectoEventTypeSchema = zod_1.z.enum([ + 'BRIDGE_READY', + 'EXTENSION_REGISTERED', + 'WORKSPACE_REGISTERED', + 'PROJECT_STATUS', + 'RUN_REQUESTED', + 'RUN_COMMAND_IN_EDITOR', + 'STOP_RUN_IN_EDITOR', + 'REVEAL_EDITOR_TERMINAL', + 'RUN_STATUS', + 'ERROR', +]); +exports.BridgeAuthStateSchema = zod_1.z.object({ + protocolVersion: zod_1.z.literal(exports.PROTOCOL_VERSION), + host: zod_1.z.literal('127.0.0.1'), + port: zod_1.z.number().int().min(1).max(65_535), + token: zod_1.z.string().min(24), + updatedAt: zod_1.z.string().datetime(), +}); +exports.ExtensionRegistrationSchema = zod_1.z.object({ + protocolVersion: zod_1.z.string().min(1), + extensionId: zod_1.z.string().min(1), + extensionVersion: zod_1.z.string().min(1), + editorName: zod_1.z.string().min(1), + editorVersion: zod_1.z.string().min(1).optional(), + machineName: zod_1.z.string().min(1).optional(), + workspacePaths: zod_1.z.array(zod_1.z.string().min(1)).default([]), +}); +exports.WorkspaceRegistrationSchema = zod_1.z.object({ + protocolVersion: zod_1.z.string().min(1), + extensionId: zod_1.z.string().min(1), + editorName: zod_1.z.string().min(1), + workspacePath: zod_1.z.string().min(1), +}); +exports.ProjectStatusRequestSchema = zod_1.z.object({ + workspacePath: zod_1.z.string().min(1), +}); +exports.LaunchProfileSummarySchema = zod_1.z.object({ + id: zod_1.z.string().min(1), + name: zod_1.z.string().min(1), + commandIds: zod_1.z.array(zod_1.z.string().min(1)).default([]), +}); +exports.LaunchCommandSummarySchema = zod_1.z.object({ + id: zod_1.z.string().min(1), + label: zod_1.z.string().min(1), + command: zod_1.z.string().min(1), + cwd: zod_1.z.string().min(1), +}); +exports.ProjectStatusResponseSchema = zod_1.z.object({ + matched: zod_1.z.boolean(), + project: zod_1.z + .object({ + id: zod_1.z.string().min(1), + name: zod_1.z.string().min(1), + path: zod_1.z.string().min(1), + launchProfiles: zod_1.z.array(exports.LaunchProfileSummarySchema).default([]), + commands: zod_1.z.array(exports.LaunchCommandSummarySchema).default([]), + }) + .nullable(), +}); +exports.RunProfileRequestSchema = zod_1.z.object({ + projectId: zod_1.z.string().min(1), + profileId: zod_1.z.string().min(1), + source: zod_1.z.enum(['desktop', 'extension']).default('extension'), +}); +exports.RunCommandRequestSchema = zod_1.z.object({ + projectId: zod_1.z.string().min(1), + commandId: zod_1.z.string().min(1), + source: zod_1.z.enum(['desktop', 'extension']).default('extension'), +}); +exports.EditorTerminalLocationSchema = zod_1.z.enum(['panel', 'editor']); +exports.EditorTerminalCommandSchema = zod_1.z.object({ + jobId: zod_1.z.string().min(1), + projectId: zod_1.z.string().min(1), + projectName: zod_1.z.string().min(1), + workspacePath: zod_1.z.string().min(1), + commandId: zod_1.z.string().min(1), + label: zod_1.z.string().min(1), + command: zod_1.z.string().min(1), + cwd: zod_1.z.string().min(1), + terminalLocation: exports.EditorTerminalLocationSchema.default('panel'), +}); +exports.EditorRunStatusSchema = zod_1.z.enum([ + 'accepted', + 'running', + 'completed', + 'failed', + 'stopped', + 'terminal_closed', +]); +exports.EditorRunEventSchema = zod_1.z.object({ + jobId: zod_1.z.string().min(1), + projectId: zod_1.z.string().min(1).optional(), + commandId: zod_1.z.string().min(1).optional(), + status: exports.EditorRunStatusSchema, + message: zod_1.z.string().min(1).optional(), + exitCode: zod_1.z.number().nullable().optional(), + timestamp: zod_1.z.string().datetime().optional(), +}); +exports.EditorRunOutputKindSchema = zod_1.z.enum(['stdout', 'stderr', 'url-detected']); +exports.EditorRunOutputEventSchema = zod_1.z.object({ + jobId: zod_1.z.string().min(1), + projectId: zod_1.z.string().min(1).optional(), + commandId: zod_1.z.string().min(1).optional(), + kind: exports.EditorRunOutputKindSchema, + message: zod_1.z.string(), + url: zod_1.z.string().url().optional(), + timestamp: zod_1.z.string().datetime().optional(), +}); +exports.ProjectoCommandSchema = zod_1.z.discriminatedUnion('type', [ + zod_1.z.object({ + type: zod_1.z.literal('OPEN_PROJECT'), + projectId: zod_1.z.string().min(1), + }), + zod_1.z.object({ + type: zod_1.z.literal('RUN_PROFILE'), + projectId: zod_1.z.string().min(1), + profileId: zod_1.z.string().min(1), + }), + zod_1.z.object({ + type: zod_1.z.literal('RUN_COMMAND'), + projectId: zod_1.z.string().min(1), + commandId: zod_1.z.string().min(1), + }), + zod_1.z.object({ + type: zod_1.z.literal('REGISTER_WORKSPACE'), + workspacePath: zod_1.z.string().min(1), + editor: zod_1.z.string().min(1), + }), + zod_1.z.object({ + type: zod_1.z.literal('GET_PROJECT_STATUS'), + workspacePath: zod_1.z.string().min(1), + }), + zod_1.z.object({ + type: zod_1.z.literal('OPEN_EDITOR_TERMINAL'), + projectId: zod_1.z.string().min(1), + }), + zod_1.z.object({ + type: zod_1.z.literal('OPEN_PROJECTO_APP'), + }), +]); +exports.ProjectoEventSchema = zod_1.z.discriminatedUnion('type', [ + zod_1.z.object({ + type: zod_1.z.literal('BRIDGE_READY'), + protocolVersion: zod_1.z.string().min(1), + port: zod_1.z.number().int().min(1).max(65_535), + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('EXTENSION_REGISTERED'), + extensionId: zod_1.z.string().min(1), + editorName: zod_1.z.string().min(1), + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('WORKSPACE_REGISTERED'), + extensionId: zod_1.z.string().min(1), + workspacePath: zod_1.z.string().min(1), + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('PROJECT_STATUS'), + workspacePath: zod_1.z.string().min(1), + status: exports.ProjectStatusResponseSchema, + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('RUN_REQUESTED'), + projectId: zod_1.z.string().min(1), + profileId: zod_1.z.string().min(1).optional(), + commandId: zod_1.z.string().min(1).optional(), + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('RUN_COMMAND_IN_EDITOR'), + payload: exports.EditorTerminalCommandSchema, + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('STOP_RUN_IN_EDITOR'), + payload: zod_1.z.object({ + jobId: zod_1.z.string().min(1), + }), + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('REVEAL_EDITOR_TERMINAL'), + payload: zod_1.z.object({ + projectId: zod_1.z.string().min(1), + workspacePath: zod_1.z.string().min(1), + jobId: zod_1.z.string().min(1).optional(), + }), + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('RUN_STATUS'), + runId: zod_1.z.string().min(1), + status: zod_1.z.enum(['queued', 'running', 'completed', 'failed', 'stopped']), + message: zod_1.z.string().min(1).optional(), + timestamp: zod_1.z.string().datetime(), + }), + zod_1.z.object({ + type: zod_1.z.literal('ERROR'), + message: zod_1.z.string().min(1), + code: zod_1.z.string().min(1).optional(), + timestamp: zod_1.z.string().datetime(), + }), +]); +exports.BridgeHealthResponseSchema = zod_1.z.object({ + ok: zod_1.z.literal(true), + protocolVersion: zod_1.z.string().min(1), + extensionConnected: zod_1.z.boolean(), + registeredWorkspaceCount: zod_1.z.number().int().nonnegative(), + uptimeSeconds: zod_1.z.number().nonnegative(), +}); diff --git a/vendor/projecto-protocol/package.json b/vendor/projecto-protocol/package.json new file mode 100644 index 0000000..bd441e5 --- /dev/null +++ b/vendor/projecto-protocol/package.json @@ -0,0 +1,11 @@ +{ + "name": "projecto-protocol", + "version": "0.1.0", + "description": "Shared Projecto desktop/editor bridge protocol schemas.", + "main": "index.js", + "types": "index.d.ts", + "license": "MIT", + "dependencies": { + "zod": "^3.23.8" + } +} \ No newline at end of file