Compare commits
No commits in common. "main" and "mcp-support" have entirely different histories.
main
...
mcp-suppor
37
.github/workflows/build-windows.yml
vendored
@ -1,37 +0,0 @@
|
||||
name: Build Windows
|
||||
|
||||
# An unsigned Windows installer on demand, for testing the Windows build
|
||||
# before it is part of the release (see apps/desktop/WINDOWS.md). Signing
|
||||
# and publishing join the Release workflow in a later stage.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
make-windows:
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Provide client env for web build
|
||||
shell: bash
|
||||
run: cp apps/web/.env.example apps/web/.env
|
||||
|
||||
- name: Build and make the installer
|
||||
shell: bash
|
||||
env:
|
||||
SKIP_SIGN: "1"
|
||||
run: npm run make --workspace=@diffusionstudio/desktop
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: diffusion-studio-windows-${{ runner.arch }}
|
||||
path: apps/desktop/out/make/squirrel.windows/**
|
||||
if-no-files-found: error
|
||||
8
.github/workflows/bump-cask.yml
vendored
@ -19,14 +19,8 @@ jobs:
|
||||
if [ -z "$TAG" ]; then
|
||||
TAG=$(curl -sf https://api.github.com/repos/diffusionstudio/editor/releases/latest | jq -r .tag_name)
|
||||
fi
|
||||
# Draft releases carry a placeholder tag (untagged-<hash>); never write that into the cask.
|
||||
if ! echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
|
||||
echo "Refusing to bump cask: '$TAG' is not a vX.Y.Z tag" >&2
|
||||
exit 1
|
||||
fi
|
||||
VERSION="${TAG#v}"
|
||||
# The release event can fire before the DMG upload finishes; 404s are retried too.
|
||||
curl -sfL --retry 10 --retry-delay 30 --retry-all-errors -o app.dmg "https://github.com/diffusionstudio/editor/releases/download/${TAG}/Diffusion-Studio-arm64.dmg"
|
||||
curl -sfL -o app.dmg "https://github.com/diffusionstudio/editor/releases/download/${TAG}/Diffusion-Studio-arm64.dmg"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "sha256=$(shasum -a 256 app.dmg | cut -d' ' -f1)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
|
||||
72
.github/workflows/bump-winget.yml
vendored
@ -1,72 +0,0 @@
|
||||
name: Bump winget package
|
||||
|
||||
# Opens a pull request on microsoft/winget-pkgs for each published release,
|
||||
# the Windows counterpart of bump-cask.yml. Komac reads the manifest of the
|
||||
# version already in winget-pkgs, swaps in the new installer URL and its
|
||||
# checksum, and submits from the token owner's fork of winget-pkgs. The
|
||||
# package's first version is submitted by hand; this only updates it.
|
||||
#
|
||||
# Needs the WINGET_TOKEN secret: a classic personal access token with the
|
||||
# `public_repo` scope (Komac cannot open the pull request with a
|
||||
# fine-grained one), whose account has a fork of microsoft/winget-pkgs.
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Release tag to submit (vX.Y.Z). Empty means the latest release.
|
||||
required: false
|
||||
|
||||
env:
|
||||
PACKAGE_ID: DiffusionStudio.DiffusionStudio
|
||||
KOMAC_VERSION: 2.16.0
|
||||
KOMAC_SHA256: 7d2707fa6210f2789a3702de49fbd150b736dbf426ee0b9bc8e098736f9fd82d
|
||||
|
||||
jobs:
|
||||
bump-winget:
|
||||
if: ${{ !github.event.release.prerelease }}
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Resolve release
|
||||
id: info
|
||||
env:
|
||||
TAG: ${{ github.event.release.tag_name || inputs.tag }}
|
||||
run: |
|
||||
if [ -z "$TAG" ]; then
|
||||
TAG=$(curl -sf https://api.github.com/repos/diffusionstudio/editor/releases/latest | jq -r .tag_name)
|
||||
fi
|
||||
# Draft releases carry a placeholder tag (untagged-<hash>); never submit that.
|
||||
if ! echo "$TAG" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$'; then
|
||||
echo "Refusing to bump winget: '$TAG' is not a vX.Y.Z tag" >&2
|
||||
exit 1
|
||||
fi
|
||||
URL="https://github.com/diffusionstudio/editor/releases/download/${TAG}/Diffusion-Studio-x64-Setup.exe"
|
||||
# Komac downloads the installer to hash it; make sure it is there first (retrying like bump-cask.yml).
|
||||
curl -sfIL --retry 10 --retry-delay 30 --retry-all-errors -o /dev/null "$URL"
|
||||
echo "tag=$TAG" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
|
||||
echo "url=$URL" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Install Komac
|
||||
run: |
|
||||
curl -sfL -o komac.tar.gz "https://github.com/russellbanks/Komac/releases/download/v${KOMAC_VERSION}/komac-${KOMAC_VERSION}-x86_64-unknown-linux-gnu.tar.gz"
|
||||
echo "${KOMAC_SHA256} komac.tar.gz" | sha256sum -c -
|
||||
tar -xzf komac.tar.gz komac
|
||||
./komac --version
|
||||
|
||||
- name: Submit to winget-pkgs
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.WINGET_TOKEN }}
|
||||
VERSION: ${{ steps.info.outputs.version }}
|
||||
URL: ${{ steps.info.outputs.url }}
|
||||
TAG: ${{ steps.info.outputs.tag }}
|
||||
# On a rerun Komac finds the pull request it opened before and, in CI,
|
||||
# exits without opening another.
|
||||
run: |
|
||||
./komac update "$PACKAGE_ID" \
|
||||
--version "$VERSION" \
|
||||
--urls "$URL" \
|
||||
--release-notes-url "https://github.com/diffusionstudio/editor/releases/tag/${TAG}" \
|
||||
--submit
|
||||
103
.github/workflows/release.yml
vendored
@ -54,106 +54,3 @@ jobs:
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
run: npm run publish --workspace=@diffusionstudio/desktop
|
||||
|
||||
# Signed with Azure Artifact Signing; apps/desktop/WINDOWS.md (stage 5) has
|
||||
# the account setup and the secrets and variables this job expects. Runs
|
||||
# after the macOS job so both append their assets to the one draft release
|
||||
# instead of racing to create it. Squirrel's RELEASES file and the nupkg
|
||||
# land next to the setup exe; the updater needs all three.
|
||||
publish-windows:
|
||||
needs: publish-macos
|
||||
runs-on: windows-latest
|
||||
# The environment name is the subject of the OIDC token that Azure's
|
||||
# federated credential for this repository is bound to.
|
||||
environment: release
|
||||
permissions:
|
||||
contents: write
|
||||
id-token: write # OIDC sign-in to Azure, no client secret
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
|
||||
- name: Check versions match tag
|
||||
shell: bash
|
||||
run: |
|
||||
TAG="${GITHUB_REF_NAME#v}"
|
||||
for PKG in package.json apps/desktop/package.json apps/cli/package.json apps/web/package.json; do
|
||||
V="$(node -p "require('./$PKG').version")"
|
||||
if [ "$V" != "$TAG" ]; then
|
||||
echo "Version mismatch in $PKG: $V, tag is $TAG"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- run: npm ci
|
||||
|
||||
- name: Provide client env for web build
|
||||
shell: bash
|
||||
run: cp apps/web/.env.example apps/web/.env
|
||||
|
||||
- name: Sign in to Azure
|
||||
uses: azure/login@v2
|
||||
with:
|
||||
client-id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||
tenant-id: ${{ secrets.AZURE_TENANT_ID }}
|
||||
subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||
|
||||
# signtool.exe from the newest Windows SDK on the runner (the dlib needs
|
||||
# 10.0.2261.755 or later), the Artifact Signing dlib from NuGet, and a
|
||||
# metadata file naming the account. forge.config.ts reads the three
|
||||
# paths from the environment. Authentication goes through the Azure CLI
|
||||
# session from the step above; every other credential source is
|
||||
# excluded so a misconfiguration fails fast instead of timing out.
|
||||
- name: Set up Artifact Signing
|
||||
shell: pwsh
|
||||
env:
|
||||
ENDPOINT: ${{ vars.ARTIFACT_SIGNING_ENDPOINT }}
|
||||
ACCOUNT: ${{ vars.ARTIFACT_SIGNING_ACCOUNT }}
|
||||
PROFILE: ${{ vars.ARTIFACT_SIGNING_PROFILE }}
|
||||
run: |
|
||||
$ErrorActionPreference = "Stop"
|
||||
foreach ($name in "ENDPOINT", "ACCOUNT", "PROFILE") {
|
||||
if (-not (Get-Item "env:$name").Value) { throw "Repository variable ARTIFACT_SIGNING_$name is not set" }
|
||||
}
|
||||
|
||||
$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\10.0.*\x64\signtool.exe" |
|
||||
Sort-Object { [version]$_.Directory.Parent.Name } | Select-Object -Last 1
|
||||
if (-not $signtool) { throw "signtool.exe not found in the Windows SDK" }
|
||||
|
||||
$dir = Join-Path $env:RUNNER_TEMP "artifact-signing"
|
||||
nuget install Microsoft.ArtifactSigning.Client -ExcludeVersion -OutputDirectory $dir
|
||||
$dlib = Join-Path $dir "Microsoft.ArtifactSigning.Client\bin\x64\Azure.CodeSigning.Dlib.dll"
|
||||
if (-not (Test-Path $dlib)) { throw "Artifact Signing dlib not found at $dlib" }
|
||||
|
||||
$metadata = Join-Path $dir "metadata.json"
|
||||
@{
|
||||
Endpoint = $env:ENDPOINT
|
||||
CodeSigningAccountName = $env:ACCOUNT
|
||||
CertificateProfileName = $env:PROFILE
|
||||
CorrelationId = "$env:GITHUB_REPOSITORY $env:GITHUB_REF_NAME"
|
||||
ExcludeCredentials = @(
|
||||
"EnvironmentCredential",
|
||||
"WorkloadIdentityCredential",
|
||||
"ManagedIdentityCredential",
|
||||
"SharedTokenCacheCredential",
|
||||
"VisualStudioCredential",
|
||||
"VisualStudioCodeCredential",
|
||||
"AzurePowerShellCredential",
|
||||
"AzureDeveloperCliCredential",
|
||||
"InteractiveBrowserCredential"
|
||||
)
|
||||
} | ConvertTo-Json | Set-Content -Path $metadata -Encoding utf8
|
||||
|
||||
"WINDOWS_SIGNTOOL_PATH=$($signtool.FullName)" >> $env:GITHUB_ENV
|
||||
"WINDOWS_SIGN_DLIB=$dlib" >> $env:GITHUB_ENV
|
||||
"WINDOWS_SIGN_METADATA=$metadata" >> $env:GITHUB_ENV
|
||||
|
||||
- name: Build, sign, and publish draft release
|
||||
shell: bash
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: npm run publish --workspace=@diffusionstudio/desktop
|
||||
|
||||
3
.gitignore
vendored
@ -39,5 +39,4 @@ out/
|
||||
# AI
|
||||
skills-lock.json
|
||||
.agents
|
||||
.claude
|
||||
.gstack/
|
||||
.claude
|
||||
85
README.md
@ -4,10 +4,10 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">Turn your agent into a professional video editor</p>
|
||||
<p align="center">The professional video editor built for agents</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://www.diffusion.studio/download"><img src="https://img.shields.io/badge/Download-macOS%20%7C%20Windows-161616?style=flat&labelColor=000000" alt="Download for macOS or Windows" /></a>
|
||||
<a href="https://www.diffusion.studio/download"><img src="https://img.shields.io/badge/Download-macOS%20Apple%20Silicon-161616?style=flat&logo=apple&logoColor=F8F8F8&labelColor=000000" alt="Download for macOS (Apple Silicon)" /></a>
|
||||
<a href="https://discord.com/invite/zPQJrNGuFB"><img src="https://img.shields.io/discord/1115673443141156924?style=flat&logo=discord&logoColor=F8F8F8&label=Discord&labelColor=000000&color=161616" alt="Discord" /></a>
|
||||
<a href="https://x.com/diffusionhq"><img src="https://img.shields.io/badge/Follow%20for-Updates-161616?style=flat&logo=x&logoColor=F8F8F8&labelColor=000000" alt="Follow on X" /></a>
|
||||
<a href="https://www.ycombinator.com/companies/diffusion-studio"><img src="https://img.shields.io/badge/Combinator-F24-161616?style=flat&logo=ycombinator&logoColor=F8F8F8&labelColor=000000" alt="Y Combinator F24" /></a>
|
||||
@ -49,16 +49,25 @@ The agent handles everything from there:
|
||||
Beyond finishing a cut, it covers:
|
||||
|
||||
- **Motion graphics**: explainers, promos, and title sequences
|
||||
- **Generative assets**: images, video, and voiceover, declared in code and composited into the timeline
|
||||
- **Clipping**: highlights from a long video, reformatted for social
|
||||
- **Video understanding**: summaries, scene search, quotes with timestamps
|
||||
|
||||
## How it works
|
||||
|
||||
Diffusion Studio uses [SolidJS](https://www.solidjs.com) modules as the document source. Think IDE, but it renders a video canvas instead of text.
|
||||
|
||||
Editing works both ways: change something on the canvas and the code updates; change the code and the canvas redraws.
|
||||
|
||||
The desktop app includes command-line tools that let agents watch and listen to footage, edit it on a timeline, and render the result.
|
||||
|
||||
## Getting started
|
||||
|
||||
Download the desktop app for macOS (Apple Silicon) or Windows (x64), it walks you through setting everything up:
|
||||
Download the desktop app, it walks you through setting everything up:
|
||||
|
||||
<a href="https://www.diffusion.studio/download"><img src="https://img.shields.io/badge/Download-Diffusion%20Studio-161616?style=for-the-badge&labelColor=000000" alt="Download Diffusion Studio" /></a>
|
||||
<a href="https://www.diffusion.studio/download"><img src="https://img.shields.io/badge/Download-Diffusion%20Studio-161616?style=for-the-badge&logo=apple&logoColor=F8F8F8&labelColor=000000" alt="Download Diffusion Studio" /></a>
|
||||
|
||||
Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. The app registers its MCP server with your agent, so just ask for what you want in plain language.
|
||||
Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. The app registers its MCP server with your agent, so just ask for what you want in plain language. Every session's instructions carry the editing and watching skills, so the agent reads the guidance it needs up front. `dapi` is the same set of tools as a CLI.
|
||||
|
||||
## Prompt examples
|
||||
|
||||
@ -66,7 +75,7 @@ Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. The app registers i
|
||||
<summary><b>Motion graphics</b></summary>
|
||||
|
||||
```text
|
||||
Create a polished, 20-second SaaS product promo video for https://typesafe.ai/. Use the website’s branding and highlight the product’s main benefit with animated UI mockups, concise on-screen text, and smooth transitions. End with a clear call to action.
|
||||
Create a ~20-second promo for vercel-labs/native in Vercel's presentation style. Research its official website, GitHub, and brand guidelines; use authentic assets and verified product features, with crisp typography, polished motion, and a strong final CTA.
|
||||
```
|
||||
|
||||
```text
|
||||
@ -122,17 +131,9 @@ Both were created by prompting. The compositions are published in [diffusionstud
|
||||
| --- | --- |
|
||||
| <img src="assets/launch-video.gif" alt="Launch video" width="420" /> | <img src="assets/raise-announcement.gif" alt="Raise announcement" width="420" /> |
|
||||
|
||||
## How it works
|
||||
|
||||
Diffusion Studio uses [SolidJS](https://www.solidjs.com) modules as the document source. Think IDE, but it renders a video canvas instead of text.
|
||||
|
||||
Editing works both ways: change something on the canvas and the code updates; change the code and the canvas redraws.
|
||||
|
||||
The desktop app includes command-line tools that let agents watch and listen to footage, edit it on a timeline, and render the result.
|
||||
|
||||
## Compositions as code
|
||||
|
||||
A project is a folder of that JSX: `open` a folder once (`diffusion open <dir>` from a shell), then edit the files. Saving recompiles the entry file and mounts it directly into the editor's ECS.
|
||||
A project is a folder of that JSX: `open` a folder once (`dapi open <dir>` from a shell), then edit the files. Saving recompiles the entry file and mounts it directly into the editor's ECS.
|
||||
|
||||
Every element carries an `id`, which is how the write-back finds its target: a rect dragged on the canvas, a clip trimmed on the timeline, or a retyped line lands as a prop on the element that authored it.
|
||||
|
||||
@ -140,6 +141,10 @@ The root is a `<stage>` holding one `<scene>` per frame you cut in:
|
||||
|
||||
```tsx
|
||||
import { For } from "solid-js";
|
||||
import { generate } from "@diffusionstudio/jsx";
|
||||
|
||||
const hero = generate.image({ prompt: "A neon city at night, cinematic", aspectRatio: "16:9" });
|
||||
const motion = generate.video({ prompt: "slow camera push-in", startFrame: hero, duration: 5 });
|
||||
|
||||
const TITLES = [
|
||||
{ text: "The Grid", start: 0, end: 2.5 },
|
||||
@ -150,7 +155,7 @@ export default function Project() {
|
||||
return (
|
||||
<stage camera={[0.3, 0, 0, 0.3, 85, 150]}>
|
||||
<scene name="Intro" width={1920} height={1080} fill="black" active>
|
||||
<video src="footage/city.mp4" start={0} end={5} width={1920} height={1080} />
|
||||
<video src={motion} start={0} end={5} width={1920} height={1080} />
|
||||
<For each={TITLES}>
|
||||
{(t) => (
|
||||
<text
|
||||
@ -180,35 +185,36 @@ Everything a mount produces stays a first-class editor node, so a person can pic
|
||||
Cutting footage requires understanding it. The app exposes the inspection tools an agent needs to work with media it cannot watch — as MCP tools, and as the same commands in a shell:
|
||||
|
||||
```sh
|
||||
diffusion probe clip.mp4 # container + codec metadata, like ffprobe
|
||||
diffusion grab clip.mp4 -t 0 12 45 # decode frames to PNGs
|
||||
diffusion filmstrip clip.mp4 # grid of video frames
|
||||
diffusion waveform track.mp3 # audio waveform, silence flagged
|
||||
diffusion transcribe interview.wav # timed, word-level transcript
|
||||
diffusion listen interview.mp4 -p "what is said in the intro?" # ask a multimodal model
|
||||
diffusion capture intro -t 0 2 4 # the frames a render would produce, by scene id
|
||||
dapi media probe clip.mp4 # container + codec metadata, like ffprobe
|
||||
dapi media grab clip.mp4 -t 0 12 45 # decode frames to PNGs
|
||||
dapi media filmstrip clip.mp4 # grid of video frames
|
||||
dapi media waveform track.mp3 # audio waveform, silence flagged
|
||||
dapi media transcribe interview.wav # timed, word-level transcript
|
||||
dapi media listen interview.mp4 -p "what is said in the intro?" # ask a multimodal model
|
||||
dapi capture intro -t 0 2 4 # the frames a render would produce, by scene id
|
||||
```
|
||||
|
||||
Each command is the MCP tool of the same name: `diffusion grab` is `grab`, `--per-sheet` is `perSheet`.
|
||||
Each command is the MCP tool of the same name: `dapi media grab` is `media_grab`, `--per-sheet` is `perSheet`.
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `diffusion open` | Launch the app and open (or create) a project folder, anywhere on disk |
|
||||
| `diffusion context` | Summary of app state |
|
||||
| `diffusion capture` | Render frames of a scene, as an export would, to a labelled contact sheet or one PNG per position |
|
||||
| `diffusion check` | Check a node's subtree for structural mistakes (black-frame gaps, never-visible nodes, failed sources) and report subtree stats |
|
||||
| `diffusion probe` / `grab` / `filmstrip` / `waveform` / `transcribe` / `listen` | Inspect a file by id or path |
|
||||
| `diffusion fonts` | Discover Google Fonts and local font families |
|
||||
| `diffusion screenshot` / `diffusion logs` | The app itself: capture the window, read recent console output |
|
||||
| `diffusion report` | Report a bug in the tools or the app: diagnostics bundled, filed as a GitHub issue via `gh` |
|
||||
| `dapi open` | Launch the app and open (or create) a project folder, anywhere on disk |
|
||||
| `dapi context` | Summary of app state |
|
||||
| `dapi capture` | Render frames of a scene, as an export would, to a labelled contact sheet or one PNG per position |
|
||||
| `dapi check` | Check a node's subtree for structural mistakes (black-frame gaps, never-visible nodes, failed sources) and report subtree stats |
|
||||
| `dapi media …` | Inspect a file by id or path: `probe`, `grab`, `filmstrip`, `waveform`, `transcribe`, `listen` |
|
||||
| `dapi models` / `dapi voices` / `dapi fonts` | Discover generation models, speech voices, local fonts |
|
||||
| `dapi screenshot` / `dapi logs` | The app itself: capture the window, read recent console output |
|
||||
| `dapi whoami` | The authenticated account |
|
||||
| `dapi report` | Report a bug in the tools or the app: diagnostics bundled, filed as a GitHub issue via `gh` |
|
||||
|
||||
Conventions throughout: every result is one JSON object, the same structured content the MCP tool returns; errors go to stderr with exit code `1`. Everything is built to be piped, grepped, and driven by a program.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Tool reference](docs/reference/tools/README.md): every tool and CLI command, its options, and its output
|
||||
- [JSX reference](docs/reference/jsx/README.md): the composition markup with elements, timing, paints, and captions
|
||||
- [Examples](docs/examples/README.md): runnable compositions, from basic scenes to three.js and raw WebGPU
|
||||
- [JSX reference](docs/reference/jsx/README.md): the composition markup with elements, timing, paints, generative assets, and captions
|
||||
- [Examples](docs/examples/README.md): runnable compositions, from basic scenes and generative assets to three.js and raw WebGPU
|
||||
|
||||
## Repository layout
|
||||
|
||||
@ -216,10 +222,10 @@ Conventions throughout: every result is one JSON object, the same structured con
|
||||
| --- | --- | --- |
|
||||
| `apps/web` | `@diffusionstudio/web` | The editor UI (Solid + Vite) |
|
||||
| `apps/desktop` | `@diffusionstudio/desktop` | Electron shell hosting the editor |
|
||||
| `apps/cli` | `@diffusionstudio/cli` | The `diffusion` CLI (`dapi` alias): a client of the app's MCP server |
|
||||
| `apps/cli` | `@diffusionstudio/cli` | The `dapi` CLI: a client of the app's MCP server |
|
||||
| `packages/runtime` | `@diffusionstudio/runtime` | Headless editor runtime: the koota world, traits, actions, systems, media decoding, capture. No DOM, no Solid |
|
||||
| `packages/reconciler` | `@diffusionstudio/reconciler` | Evaluates a compiled project bundle and reconciles its element tree onto runtime entities, via Solid's universal renderer |
|
||||
| `packages/jsx` | `@diffusionstudio/jsx` | The authoring API: element vocabulary and types |
|
||||
| `packages/jsx` | `@diffusionstudio/jsx` | The authoring API: element vocabulary, types, and generated assets (`generate.*`) |
|
||||
| `packages/assets` | `@diffusionstudio/assets` | A project's asset library: the `assets.yml` manifest, content hashing, probing, resolution |
|
||||
| `packages/encoder` | `@diffusionstudio/encoder` | Offline video/audio/image encoding over runtime worlds (mediabunny) |
|
||||
| `packages/koota-solid` | `@diffusionstudio/koota-solid` | Solid bindings for koota, ported from `@koota/react` |
|
||||
@ -238,18 +244,19 @@ cp apps/web/.env.example apps/web/.env # required: the app won't run without i
|
||||
npm run dev
|
||||
```
|
||||
|
||||
To put `diffusion` (and its `dapi` alias) on your PATH, link it once (`unlink` undoes it):
|
||||
To put `dapi` on your PATH (macOS/Homebrew layout; adjust the link target for other setups), link it once:
|
||||
|
||||
```sh
|
||||
npm run link --workspace=@diffusionstudio/cli
|
||||
npm run symlink:create --workspace=@diffusionstudio/cli
|
||||
```
|
||||
|
||||
The link points at the CLI build, which `npm run dev:desktop` refreshes on every start, so the linked `dapi` always runs the latest code.
|
||||
|
||||
Before sending a PR:
|
||||
|
||||
```sh
|
||||
npm run check # typecheck all workspaces
|
||||
npm run lint # lint all workspaces
|
||||
npm run test # ensure tests are green
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
@ -1,17 +1,16 @@
|
||||
{
|
||||
"name": "@diffusionstudio/cli",
|
||||
"private": true,
|
||||
"version": "0.216.0",
|
||||
"version": "0.205.0",
|
||||
"license": "MPL-2.0",
|
||||
"bin": {
|
||||
"diffusion": "./dist/index.js",
|
||||
"dapi": "./dist/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=cjs --outfile=dist/index.js && node -e \"process.platform !== 'win32' && require('node:fs').chmodSync('dist/index.js', 0o755)\"",
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=cjs --outfile=dist/index.js && chmod +x dist/index.js",
|
||||
"check": "tsc --noEmit",
|
||||
"link": "npm run build && node scripts/dev-link.mjs",
|
||||
"unlink": "node scripts/dev-link.mjs --remove"
|
||||
"symlink:remove": "rm -f /opt/homebrew/bin/dapi",
|
||||
"symlink:create": "npm run build && ln -sf \"$PWD/dist/index.js\" /opt/homebrew/bin/dapi"
|
||||
},
|
||||
"dependencies": {
|
||||
"@diffusionstudio/dapi": "*",
|
||||
|
||||
@ -1,119 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Puts `diffusion` (and a `dapi` alias) on the PATH, running this workspace's
|
||||
// build, for developing against the CLI. `npm run dev:desktop` rebuilds the
|
||||
// CLI on every start, so the link keeps running the latest code. `dapi` is
|
||||
// where a dev build of the desktop app looks for the binary it registers
|
||||
// with agents and reports in the settings CLI card (apps/desktop/src/cli-install.ts
|
||||
// and mcp-install.ts), so that name and path are load-bearing; `diffusion` is
|
||||
// added alongside it purely for typing at a shell.
|
||||
//
|
||||
// macOS symlinks in Homebrew's bin, `/opt/homebrew/bin/{dapi,diffusion}`,
|
||||
// which is user-writable, so no admin prompt. The packaged app uses
|
||||
// `/usr/local/bin` instead and the two never collide.
|
||||
// Windows `%LOCALAPPDATA%\DiffusionStudio\bin\{dapi,diffusion}.cmd`, the same
|
||||
// file the packaged app keeps its own shim in (apps/desktop/src/cli-windows.ts).
|
||||
// A packaged app rewrites the `dapi` one on launch, so run this again
|
||||
// after using one. The folder is added to the user PATH the way the
|
||||
// packaged app's "Install CLI" does it; `--remove` leaves that
|
||||
// entry, since a packaged install may still use it.
|
||||
//
|
||||
// node scripts/dev-link.mjs create the link
|
||||
// node scripts/dev-link.mjs --remove delete it
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, win32 } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const script = join(dirname(fileURLToPath(import.meta.url)), "..", "dist", "index.js");
|
||||
const remove = process.argv.includes("--remove");
|
||||
|
||||
const NAMES = ["dapi", "diffusion"];
|
||||
|
||||
if (process.platform === "win32") {
|
||||
const local = process.env.LOCALAPPDATA || join(homedir(), "AppData", "Local");
|
||||
const dir = join(local, "DiffusionStudio", "bin");
|
||||
const shims = NAMES.map((name) => join(dir, `${name}.cmd`));
|
||||
|
||||
if (remove) {
|
||||
for (const shim of shims) {
|
||||
rmSync(shim, { force: true });
|
||||
console.log(`dev-link: removed ${shim}`);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const batch = (path) => path.replaceAll("%", "%%");
|
||||
mkdirSync(dir, { recursive: true });
|
||||
for (const shim of shims) {
|
||||
writeFileSync(shim, ["@echo off", "setlocal", `node "${batch(script)}" %*`, ""].join("\r\n"));
|
||||
console.log(`dev-link: ${shim} -> ${script}`);
|
||||
}
|
||||
|
||||
if (addToUserPath(dir)) {
|
||||
console.log(`dev-link: added ${dir} to your PATH; open a new terminal to run \`diffusion\`.`);
|
||||
}
|
||||
} else if (process.platform === "darwin") {
|
||||
const dir = "/opt/homebrew/bin";
|
||||
const links = NAMES.map((name) => join(dir, name));
|
||||
|
||||
if (remove) {
|
||||
for (const link of links) {
|
||||
rmSync(link, { force: true });
|
||||
console.log(`dev-link: removed ${link}`);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (!existsSync(dir)) {
|
||||
console.error(`dev-link: ${dir} does not exist (Homebrew is not installed, or is an Intel install); ` +
|
||||
`the dev build of the app only recognises a link there.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
for (const link of links) {
|
||||
rmSync(link, { force: true });
|
||||
symlinkSync(script, link);
|
||||
console.log(`dev-link: ${link} -> ${script}`);
|
||||
}
|
||||
} else {
|
||||
console.error(`dev-link: no link location for ${process.platform}; put ${script} on your PATH yourself.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// The user PATH in HKCU\Environment, edited the same way as
|
||||
// apps/desktop/src/cli-windows.ts: through the registry, so the %VARIABLE%
|
||||
// entries already there stay unexpanded, with a throwaway variable deletion
|
||||
// to make .NET broadcast the change to new terminals. Returns whether the
|
||||
// entry was added.
|
||||
function addToUserPath(dir) {
|
||||
const normalize = (entry) => win32.normalize(entry).replace(/[\\/]+$/, "").toLowerCase();
|
||||
const powershell = (script, env) =>
|
||||
execFileSync(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
|
||||
{ env: { ...process.env, ...env }, windowsHide: true, encoding: "utf8" },
|
||||
);
|
||||
|
||||
const current = powershell(`
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
|
||||
[Console]::Out.Write($key.GetValue('Path', '', 'DoNotExpandEnvironmentNames'))
|
||||
`);
|
||||
const entries = current.split(";").filter((entry) => entry.trim() !== "");
|
||||
if (entries.some((entry) => normalize(entry) === normalize(dir))) return false;
|
||||
|
||||
powershell(
|
||||
`
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
$kind = if ($key.GetValueNames() -contains 'Path') { $key.GetValueKind('Path') } else { 'ExpandString' }
|
||||
$key.SetValue('Path', $env:DAPI_USER_PATH, $kind)
|
||||
[Environment]::SetEnvironmentVariable('DAPI_PATH_BROADCAST', $null, 'User')
|
||||
`,
|
||||
{ DAPI_USER_PATH: [...entries, dir].join(";") },
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@ -2,7 +2,7 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { execFile } from "node:child_process";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { MCP_URL } from "@diffusionstudio/dapi";
|
||||
@ -12,14 +12,12 @@ import type { ToolInput, ToolName, ToolOutput } from "@diffusionstudio/dapi";
|
||||
|
||||
export const APP_NAME = "Diffusion Studio";
|
||||
|
||||
// Renders, media analysis and file transfers outlive the 60s default.
|
||||
// Renders and AI generation outlive the 60s default.
|
||||
const TIMEOUTS: Record<string, number> = {
|
||||
export: 3_600_000,
|
||||
capture: 600_000,
|
||||
transcribe: 600_000,
|
||||
listen: 600_000,
|
||||
generate: 600_000,
|
||||
job: 600_000,
|
||||
media_transcribe: 600_000,
|
||||
media_listen: 600_000,
|
||||
};
|
||||
|
||||
/**
|
||||
@ -44,7 +42,7 @@ export async function call<N extends ToolName>(name: N, input: ToolInput<N>): Pr
|
||||
}
|
||||
return result.structuredContent as ToolOutput<N>;
|
||||
} finally {
|
||||
await client.close().catch(() => { });
|
||||
await client.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
@ -54,14 +52,14 @@ export async function ping(): Promise<void> {
|
||||
try {
|
||||
await client.ping();
|
||||
} finally {
|
||||
await client.close().catch(() => { });
|
||||
await client.close().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
// Connecting is where "the app is not running" shows up: the `initialize`
|
||||
// request's fetch is refused, see `isAppDown`.
|
||||
async function connect(): Promise<Client> {
|
||||
const client = new Client({ name: "diffusion", version });
|
||||
const client = new Client({ name: "dapi", version });
|
||||
await client.connect(new StreamableHTTPClientTransport(new URL(MCP_URL)));
|
||||
return client;
|
||||
}
|
||||
@ -79,40 +77,22 @@ export function isAppDown(e: unknown): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
function launchWin32(background: boolean): Promise<boolean> {
|
||||
if (!process.versions.electron) return Promise.resolve(false);
|
||||
const { ELECTRON_RUN_AS_NODE: _, ...env } = process.env;
|
||||
return new Promise((res) => {
|
||||
const child = spawn(process.execPath, background ? ["--hidden"] : [], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
env,
|
||||
});
|
||||
child.once("error", () => res(false));
|
||||
child.once("spawn", () => {
|
||||
child.unref();
|
||||
res(true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function launchDarwin(background: boolean): Promise<boolean> {
|
||||
/**
|
||||
* Launches the app, or surfaces the running instance: `open -a` on a running
|
||||
* app only activates it, so this is safe to always run. macOS only; elsewhere
|
||||
* it resolves false and the caller falls through to the connection.
|
||||
*
|
||||
* The bundled `dapi` runs as Electron with ELECTRON_RUN_AS_NODE=1, and `open`
|
||||
* hands its environment to the app it launches — left in, the app boots as
|
||||
* plain Node and never answers.
|
||||
*/
|
||||
export function launchApp(background: boolean): Promise<boolean> {
|
||||
if (process.platform !== "darwin") return Promise.resolve(false);
|
||||
const args = background ? ["-g", "-a", APP_NAME, "--args", "--hidden"] : ["-a", APP_NAME];
|
||||
const { ELECTRON_RUN_AS_NODE: _, ...env } = process.env;
|
||||
return new Promise((res) => execFile("open", args, { env }, (err) => res(!err)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Launches the app, or surfaces the running instance
|
||||
*/
|
||||
export function launchApp(background: boolean): Promise<boolean> {
|
||||
if (process.platform === "win32") return launchWin32(background);
|
||||
if (process.platform === "darwin") return launchDarwin(background);
|
||||
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bridges the cold-start gap after launching the app: retries while the app
|
||||
* looks down, until it answers a ping.
|
||||
|
||||
@ -5,7 +5,7 @@
|
||||
|
||||
import { existsSync } from "node:fs";
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
import { Argument, Command } from "commander";
|
||||
import { Command } from "commander";
|
||||
import { z } from "zod";
|
||||
import { version } from "../../../package.json";
|
||||
import { MCP_URL, toolByName } from "@diffusionstudio/dapi";
|
||||
@ -66,55 +66,25 @@ function assetPath(ref: string): string {
|
||||
return ref;
|
||||
}
|
||||
|
||||
/** Parsed JSON, or a failure naming what was being read. */
|
||||
function json(value: string, what: string): unknown {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch (e) {
|
||||
fail(`${what} is not valid JSON: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Every `{ "path": … }` file reference in a request, resolved as `assetPath` does; the rest untouched. */
|
||||
function resolveFileRefs(value: unknown): unknown {
|
||||
if (Array.isArray(value)) return value.map(resolveFileRefs);
|
||||
if (typeof value !== "object" || value === null) return value;
|
||||
const entries = Object.entries(value);
|
||||
if (entries.length === 1 && entries[0]![0] === "path" && typeof entries[0]![1] === "string") return { path: assetPath(entries[0]![1]) };
|
||||
return Object.fromEntries(entries.map(([key, item]) => [key, resolveFileRefs(item)]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Where generated files go: a path spelled as one on disk
|
||||
* (absolute, or starting with `.`) resolves against the working directory;
|
||||
* anything else is a library path, passed through for the app to resolve in
|
||||
* the open project.
|
||||
*/
|
||||
function libraryOrDiskPath(ref: string): string {
|
||||
return isAbsolute(ref) || ref.startsWith(".") ? resolve(ref) : ref;
|
||||
}
|
||||
|
||||
const program = new Command();
|
||||
|
||||
program
|
||||
.name("diffusion")
|
||||
.name("dapi")
|
||||
.description(
|
||||
`The Diffusion Studio CLI: understand and edit footage.
|
||||
Analyze video/audio/images and compose assets.
|
||||
Use for any media analysis or video editing task. No ffmpeg needed.`)
|
||||
`The Diffusion Studio CLI: understand, generate, and edit footage.
|
||||
Analyze video/audio/images, generate them with AI, and compose assets.
|
||||
Use for any media analysis, media generation, or video editing task. No ffmpeg needed.`)
|
||||
.version(version);
|
||||
|
||||
program
|
||||
.command("open")
|
||||
.description(
|
||||
`Launch ${APP_NAME} (or surface the running instance) and, given a path, open that folder as a project, creating the project files if the folder is not one yet. Prints the project's id, display name, and folder. Run this once before commands that need an open project.`,
|
||||
`Launch ${APP_NAME} (or surface the running instance) and, given a path, open that folder as a project, creating the project files if the folder is not one yet. Prints the project's id, display name, and folder. Run this once before commands that need an open project (capture, check, export, context, and library paths in media commands).`,
|
||||
)
|
||||
.argument("[path]", `${field("open", "dir")} (default: none — just launch the app)`)
|
||||
.option("-b, --background", "launch or keep the app in the background, without raising a window")
|
||||
.action(async (path: string | undefined, opts: { background?: boolean }) => {
|
||||
const background = opts.background ?? false;
|
||||
const running = background && (await ping().then(() => true, (e) => (isAppDown(e) ? false : appError(e))));
|
||||
const launched = !running && (await launchApp(background));
|
||||
const launched = await launchApp(opts.background ?? false);
|
||||
await (launched ? waitForApp() : ping()).catch(appError);
|
||||
if (path !== undefined) await run("open", { dir: resolve(path) });
|
||||
});
|
||||
@ -161,115 +131,97 @@ program
|
||||
if (output.issues.some((issue) => issue.severity === "error")) process.exitCode = 1;
|
||||
});
|
||||
|
||||
program
|
||||
.command("probe")
|
||||
.description(describe("probe"))
|
||||
.argument("<path>", field("probe", "path"))
|
||||
.action((ref: string) => run("probe", { path: assetPath(ref) }));
|
||||
|
||||
program
|
||||
.command("transcribe")
|
||||
.description(describe("transcribe"))
|
||||
.argument("<path>", field("transcribe", "path"))
|
||||
.option("-o, --output <path>", field("transcribe", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"transcribe">, "path">) =>
|
||||
run("transcribe", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
const media = program
|
||||
.command("media")
|
||||
.alias("m")
|
||||
.description(
|
||||
"Inspect a media file by path, without adding it to the project: probe metadata, transcribe speech, grab frames, render visual previews, and analyze with multimodal models. Local files work with or without an open project; library paths need one.",
|
||||
);
|
||||
|
||||
program
|
||||
media
|
||||
.command("probe")
|
||||
.description(describe("media_probe"))
|
||||
.argument("<path>", field("media_probe", "path"))
|
||||
.action((ref: string) => run("media_probe", { path: assetPath(ref) }));
|
||||
|
||||
media
|
||||
.command("transcribe")
|
||||
.description(describe("media_transcribe"))
|
||||
.argument("<path>", field("media_transcribe", "path"))
|
||||
.option("-o, --output <path>", field("media_transcribe", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"media_transcribe">, "path">) =>
|
||||
run("media_transcribe", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
);
|
||||
|
||||
media
|
||||
.command("grab")
|
||||
.alias("sample")
|
||||
.description(describe("grab"))
|
||||
.argument("<path>", field("grab", "path"))
|
||||
.option("-t, --times <time...>", field("grab", "times"))
|
||||
.option("-c, --count <n>", field("grab", "count"), numeric)
|
||||
.option("-a, --auto", field("grab", "auto"))
|
||||
.option("-s, --start <time>", field("grab", "start"))
|
||||
.option("-e, --end <time>", field("grab", "end"))
|
||||
.option("-q, --quality <preset>", field("grab", "quality"))
|
||||
.option("-S, --separate", field("grab", "separate"))
|
||||
.option("--per-sheet <n>", field("grab", "perSheet"), numeric)
|
||||
.option("--uncapped", field("grab", "uncapped"))
|
||||
.option("-o, --output <dir>", field("grab", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"grab">, "path">) =>
|
||||
run("grab", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
.description(describe("media_grab"))
|
||||
.argument("<path>", field("media_grab", "path"))
|
||||
.option("-t, --times <time...>", field("media_grab", "times"))
|
||||
.option("-c, --count <n>", field("media_grab", "count"), numeric)
|
||||
.option("-a, --auto", field("media_grab", "auto"))
|
||||
.option("-s, --start <time>", field("media_grab", "start"))
|
||||
.option("-e, --end <time>", field("media_grab", "end"))
|
||||
.option("-q, --quality <preset>", field("media_grab", "quality"))
|
||||
.option("-S, --separate", field("media_grab", "separate"))
|
||||
.option("--per-sheet <n>", field("media_grab", "perSheet"), numeric)
|
||||
.option("--uncapped", field("media_grab", "uncapped"))
|
||||
.option("-o, --output <dir>", field("media_grab", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"media_grab">, "path">) =>
|
||||
run("media_grab", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
);
|
||||
|
||||
program
|
||||
media
|
||||
.command("filmstrip")
|
||||
.alias("film")
|
||||
.description(describe("filmstrip"))
|
||||
.argument("<path>", field("filmstrip", "path"))
|
||||
.option("-s, --start <time>", field("filmstrip", "start"))
|
||||
.option("-e, --end <time>", field("filmstrip", "end"))
|
||||
.option("-x, --scale <factor>", field("filmstrip", "scale"), numeric)
|
||||
.option("-o, --output <path>", field("filmstrip", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"filmstrip">, "path">) =>
|
||||
run("filmstrip", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
.description(describe("media_filmstrip"))
|
||||
.argument("<path>", field("media_filmstrip", "path"))
|
||||
.option("-s, --start <time>", field("media_filmstrip", "start"))
|
||||
.option("-e, --end <time>", field("media_filmstrip", "end"))
|
||||
.option("-x, --scale <factor>", field("media_filmstrip", "scale"), numeric)
|
||||
.option("-o, --output <path>", field("media_filmstrip", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"media_filmstrip">, "path">) =>
|
||||
run("media_filmstrip", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
);
|
||||
|
||||
program
|
||||
media
|
||||
.command("waveform")
|
||||
.alias("wave")
|
||||
.description(describe("waveform"))
|
||||
.argument("<path>", field("waveform", "path"))
|
||||
.option("-s, --start <time>", field("waveform", "start"))
|
||||
.option("-e, --end <time>", field("waveform", "end"))
|
||||
.option("-x, --scale <factor>", field("waveform", "scale"), numeric)
|
||||
.option("-o, --output <path>", field("waveform", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"waveform">, "path">) =>
|
||||
run("waveform", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
.description(describe("media_waveform"))
|
||||
.argument("<path>", field("media_waveform", "path"))
|
||||
.option("-s, --start <time>", field("media_waveform", "start"))
|
||||
.option("-e, --end <time>", field("media_waveform", "end"))
|
||||
.option("-x, --scale <factor>", field("media_waveform", "scale"), numeric)
|
||||
.option("-o, --output <path>", field("media_waveform", "output"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"media_waveform">, "path">) =>
|
||||
run("media_waveform", { path: assetPath(ref), ...opts, output: opts.output && resolve(opts.output) }),
|
||||
);
|
||||
|
||||
program
|
||||
media
|
||||
.command("listen")
|
||||
.description(describe("listen"))
|
||||
.argument("<path>", field("listen", "path"))
|
||||
.option("-p, --prompt <str>", field("listen", "prompt"))
|
||||
.option("-s, --start <time>", field("listen", "start"))
|
||||
.option("-e, --end <time>", field("listen", "end"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"listen">, "path">) => run("listen", { path: assetPath(ref), ...opts }));
|
||||
.description(describe("media_listen"))
|
||||
.argument("<path>", field("media_listen", "path"))
|
||||
.option("-p, --prompt <str>", field("media_listen", "prompt"))
|
||||
.option("-s, --start <time>", field("media_listen", "start"))
|
||||
.option("-e, --end <time>", field("media_listen", "end"))
|
||||
.action((ref: string, opts: Omit<ToolInput<"media_listen">, "path">) => run("media_listen", { path: assetPath(ref), ...opts }));
|
||||
|
||||
program
|
||||
.command("generate")
|
||||
.alias("gen")
|
||||
.description(describe("generate"))
|
||||
.addArgument(new Argument("<model>", field("generate", "model")).choices(toolByName("generate").input.shape.model.options))
|
||||
.argument(
|
||||
"[fields]",
|
||||
`the model's other fields as one JSON object, e.g. '{"aspectRatio":"16:9","images":[{"path":"./ref.png"}]}'; a { "path" } that exists relative to the working directory is sent as its absolute path; an "audio" field also takes { "scene": "<id>" }, the scene's mix`,
|
||||
)
|
||||
.option("-p, --prompt <text>", "the request's `prompt`, without JSON quoting; wins over one in the fields")
|
||||
.option(
|
||||
"-o, --output <path>",
|
||||
`${field("generate", "output")}; a path starting with . resolves against the working directory`,
|
||||
)
|
||||
.option("--max-credits <n>", field("generate", "maxCredits"), numeric)
|
||||
.option("--estimate", field("generate", "estimate"))
|
||||
.action((model: ToolInput<"generate">["model"], fields: string | undefined, opts: { prompt?: string; output?: string; maxCredits?: number; estimate?: boolean }) => {
|
||||
const parsed = fields === undefined ? {} : json(fields, "fields");
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) fail("fields must be a JSON object.");
|
||||
const request = resolveFileRefs(parsed) as Record<string, unknown>;
|
||||
return run("generate", {
|
||||
...request,
|
||||
model,
|
||||
...(opts.prompt === undefined ? {} : { prompt: opts.prompt }),
|
||||
output: opts.output && libraryOrDiskPath(opts.output),
|
||||
maxCredits: opts.maxCredits,
|
||||
estimate: opts.estimate,
|
||||
});
|
||||
});
|
||||
.command("models")
|
||||
.description(describe("models"))
|
||||
.argument("[type]", field("models", "type"))
|
||||
.action((type: ToolInput<"models">["type"]) => run("models", { type }));
|
||||
|
||||
program
|
||||
.command("job")
|
||||
.description(`${describe("job")} Exits 1 when the job failed or was canceled.`)
|
||||
.argument("<id>", field("job", "id"))
|
||||
.option("--cancel", field("job", "cancel"))
|
||||
.action(async (id: string, opts: { cancel?: boolean }) => {
|
||||
const output = await call("job", { id, cancel: opts.cancel }).catch(appError);
|
||||
console.log(JSON.stringify(output));
|
||||
if (output.status === "failed" || output.status === "canceled") process.exitCode = 1;
|
||||
});
|
||||
.command("voices")
|
||||
.description(describe("voices"))
|
||||
.action(() => run("voices", {}));
|
||||
|
||||
program
|
||||
.command("whoami")
|
||||
.description(describe("whoami"))
|
||||
.action(() => run("whoami", {}));
|
||||
|
||||
program
|
||||
.command("logs")
|
||||
@ -286,15 +238,6 @@ program
|
||||
.option("-o, --output <dir>", field("screenshot", "output"))
|
||||
.action((opts: ToolInput<"screenshot">) => run("screenshot", { output: opts.output && resolve(opts.output) }));
|
||||
|
||||
program
|
||||
.command("window")
|
||||
.description(describe("window"))
|
||||
.argument("[state]", "show (and focus) or hide the window (default: leave it as it is)")
|
||||
.action((state: string | undefined) => {
|
||||
if (state !== undefined && state !== "show" && state !== "hide") fail(`Expected show or hide, got "${state}".`);
|
||||
return run("window", { visible: state === undefined ? undefined : state === "show" });
|
||||
});
|
||||
|
||||
program
|
||||
.command("report")
|
||||
.alias("issue")
|
||||
@ -309,8 +252,6 @@ program
|
||||
.command("fonts")
|
||||
.description(describe("fonts"))
|
||||
.option("-f, --family <pattern>", field("fonts", "family"))
|
||||
.option("-p, --provider <provider>", field("fonts", "provider"))
|
||||
.option("--popular", field("fonts", "popular"))
|
||||
.option("-w, --weights <weights...>", field("fonts", "weights"))
|
||||
.option("-s, --style <style>", field("fonts", "style"))
|
||||
.option("-l, --limit <n>", field("fonts", "limit"), numeric)
|
||||
@ -319,8 +260,4 @@ program
|
||||
// Explicit argv convention: the packaged wrapper runs this bundle on
|
||||
// Electron in ELECTRON_RUN_AS_NODE mode, where commander would otherwise
|
||||
// detect Electron and drop the script path from argv.
|
||||
// The media commands used to sit under a `media` (`m`) group; drop that word so
|
||||
// scripts written against it (older projects' npm scripts) keep working.
|
||||
const argv = ["media", "m"].includes(process.argv[2] ?? "") ? process.argv.toSpliced(2, 1) : process.argv;
|
||||
|
||||
program.parse(argv, { from: "node" });
|
||||
program.parse(process.argv, { from: "node" });
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// `diffusion mcp`: the entry point for agents that only run stdio servers (Claude
|
||||
// `dapi mcp`: the entry point for agents that only run stdio servers (Claude
|
||||
// Desktop). A message pipe between stdio and the app's HTTP endpoint: each
|
||||
// side is an SDK transport, so session handling and SSE framing are theirs,
|
||||
// and nothing here looks inside a message. Stdout belongs to the protocol;
|
||||
@ -31,14 +31,14 @@ export async function runProxy(): Promise<void> {
|
||||
const stdio = new StdioServerTransport();
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
console.error(`[diffusion mcp] ${error.message}`);
|
||||
console.error(`[dapi mcp] ${error.message}`);
|
||||
process.exit(1);
|
||||
};
|
||||
|
||||
upstream.onmessage = (message: JSONRPCMessage) => void stdio.send(message).catch(fail);
|
||||
stdio.onmessage = (message: JSONRPCMessage) => void upstream.send(message).catch(fail);
|
||||
upstream.onerror = (error) => console.error(`[diffusion mcp] ${error.message}`);
|
||||
stdio.onerror = (error) => console.error(`[diffusion mcp] ${error.message}`);
|
||||
upstream.onerror = (error) => console.error(`[dapi mcp] ${error.message}`);
|
||||
stdio.onerror = (error) => console.error(`[dapi mcp] ${error.message}`);
|
||||
// The app went away (quit, or the session was closed): the agent sees EOF.
|
||||
upstream.onclose = () => process.exit(0);
|
||||
// The agent went away: tell the app, which ends the session.
|
||||
|
||||
@ -1,46 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
Application manifest embedded into "Diffusion Studio.exe" on Windows
|
||||
(win32metadata['application-manifest'] in forge.config.ts). The packager
|
||||
replaces Electron's own manifest wholesale, so this is Electron 43's
|
||||
manifest (read out of electron.exe) plus one addition: longPathAware, which
|
||||
lets the app open project folders whose paths exceed MAX_PATH, such as
|
||||
deep node_modules trees. Windows honours it only when the LongPathsEnabled
|
||||
policy is on, which it is on Windows 11 by default. Keep the rest in step
|
||||
with Electron when the Electron version changes.
|
||||
-->
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<asmv3:application xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
|
||||
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
|
||||
<disableWindowFiltering xmlns="http://schemas.microsoft.com/SMI/2011/WindowsSettings">true</disableWindowFiltering>
|
||||
</asmv3:windowsSettings>
|
||||
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">
|
||||
<dpiAware>true/pm</dpiAware>
|
||||
</asmv3:windowsSettings>
|
||||
<asmv3:windowsSettings xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">
|
||||
<longPathAware>true</longPathAware>
|
||||
</asmv3:windowsSettings>
|
||||
</asmv3:application>
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<security>
|
||||
<requestedPrivileges>
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
<dependency>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
|
||||
</dependentAssembly>
|
||||
</dependency>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}"/>
|
||||
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}"/>
|
||||
<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}"/>
|
||||
<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}"/>
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
|
||||
<maxversiontested Id="10.0.18362.0"/>
|
||||
</application>
|
||||
</compatibility>
|
||||
</assembly>
|
||||
|
Before Width: | Height: | Size: 336 KiB |
|
Before Width: | Height: | Size: 180 KiB |
|
Before Width: | Height: | Size: 37 KiB |
|
Before Width: | Height: | Size: 420 B |
|
Before Width: | Height: | Size: 755 B |
|
Before Width: | Height: | Size: 369 B |
|
Before Width: | Height: | Size: 635 B |
|
Before Width: | Height: | Size: 231 B |
@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#000" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M6.5 2.5l1.25 3.25L11 7 7.75 8.25 6.5 11.5 5.25 8.25 2 7l3.25-1.25z"/><path d="M12 10l.6 1.4 1.4.6-1.4.6L12 14l-.6-1.4L10 12l1.4-.6z" fill="#000" stroke-width="0.75"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 338 B |
|
Before Width: | Height: | Size: 397 B |
|
Before Width: | Height: | Size: 320 B |
@ -1,4 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#000" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">
|
||||
<mask id="gap"><rect width="16" height="16" fill="#fff" stroke="none"/><path d="M2.5 2.5l11 11" stroke="#000" stroke-width="3.25"/></mask>
|
||||
<g mask="url(#gap)"><path d="M1.75 8S4 3.75 8 3.75 14.25 8 14.25 8 12 12.25 8 12.25 1.75 8 1.75 8z"/><circle cx="8" cy="8" r="2"/></g><path d="M2.5 2.5l11 11"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 461 B |
|
Before Width: | Height: | Size: 615 B |
|
Before Width: | Height: | Size: 231 B |
@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#000" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">
|
||||
<rect x="2" y="3" width="12" height="10" rx="2"/><path d="M2 6h12"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 230 B |
|
Before Width: | Height: | Size: 403 B |
|
Before Width: | Height: | Size: 258 B |
@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#000" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M2 4.5A1.5 1.5 0 0 1 3.5 3h2.75l1.5 1.5h4.75A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 288 B |
|
Before Width: | Height: | Size: 353 B |
|
Before Width: | Height: | Size: 310 B |
@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#000" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M8 2v5.5"/><path d="M4.75 4.25a5.25 5.25 0 1 0 6.5 0"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 226 B |
|
Before Width: | Height: | Size: 574 B |
|
Before Width: | Height: | Size: 343 B |
@ -1,3 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="none" stroke="#000" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round">
|
||||
<circle cx="8" cy="8" r="6"/><path d="M5.5 8.25l1.75 1.75 3.25-3.5"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 231 B |
|
Before Width: | Height: | Size: 741 B |
|
Before Width: | Height: | Size: 999 B |
|
Before Width: | Height: | Size: 1.9 KiB |
@ -2,23 +2,15 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import type { ForgeConfig } from '@electron-forge/shared-types';
|
||||
import { MakerDMG } from '@electron-forge/maker-dmg';
|
||||
import { MakerSquirrel } from '@electron-forge/maker-squirrel';
|
||||
import { MakerZIP } from '@electron-forge/maker-zip';
|
||||
import { PublisherGithub } from '@electron-forge/publisher-github';
|
||||
import { copyFileSync, existsSync, readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import { arch } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
|
||||
import type { ForgeConfig } from '@electron-forge/shared-types';
|
||||
import type { MakerSquirrelConfig } from '@electron-forge/maker-squirrel';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const { version } = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'));
|
||||
|
||||
|
||||
const sign = windowsSign();
|
||||
|
||||
const config: ForgeConfig = {
|
||||
packagerConfig: {
|
||||
name: 'Diffusion Studio',
|
||||
@ -26,12 +18,6 @@ const config: ForgeConfig = {
|
||||
appCategoryType: 'public.app-category.video',
|
||||
appVersion: version,
|
||||
icon: './assets/icon',
|
||||
win32metadata: {
|
||||
CompanyName: 'Diffusion Studio',
|
||||
ProductName: 'Diffusion Studio',
|
||||
FileDescription: 'Diffusion Studio',
|
||||
'application-manifest': join(__dirname, 'assets', 'app.manifest'),
|
||||
},
|
||||
protocols: [{ name: 'Diffusion Studio', schemes: ['diffusion'] }],
|
||||
prune: false,
|
||||
ignore: (path) =>
|
||||
@ -48,28 +34,14 @@ const config: ForgeConfig = {
|
||||
osxNotarize:
|
||||
process.env.APPLE_ID && process.env.APPLE_PASSWORD && process.env.APPLE_TEAM_ID
|
||||
? {
|
||||
appleId: process.env.APPLE_ID,
|
||||
appleIdPassword: process.env.APPLE_PASSWORD,
|
||||
teamId: process.env.APPLE_TEAM_ID,
|
||||
}
|
||||
appleId: process.env.APPLE_ID,
|
||||
appleIdPassword: process.env.APPLE_PASSWORD,
|
||||
teamId: process.env.APPLE_TEAM_ID,
|
||||
}
|
||||
: undefined,
|
||||
windowsSign: sign,
|
||||
},
|
||||
makers: [
|
||||
new MakerZIP({}, ['darwin']),
|
||||
new MakerSquirrel({
|
||||
name: 'DiffusionStudio',
|
||||
authors: 'Diffusion Studio',
|
||||
description: 'The professional video editor built for agents',
|
||||
exe: 'Diffusion Studio.exe',
|
||||
setupExe: `Diffusion-Studio-${process.arch}-Setup.exe`,
|
||||
setupIcon: './assets/icon.ico',
|
||||
loadingGif: './assets/install-spinner.gif',
|
||||
// Shown by Add/Remove Programs; Squirrel only takes a URL.
|
||||
iconUrl: 'https://raw.githubusercontent.com/diffusionstudio/editor/main/apps/desktop/assets/icon.ico',
|
||||
noMsi: true,
|
||||
windowsSign: sign,
|
||||
}),
|
||||
new MakerDMG({
|
||||
name: `Diffusion-Studio-${process.arch}`,
|
||||
icon: './assets/icon.icns',
|
||||
@ -92,55 +64,6 @@ const config: ForgeConfig = {
|
||||
draft: true,
|
||||
}),
|
||||
],
|
||||
hooks: {
|
||||
prePackage: async () => {
|
||||
if (process.platform === 'win32' && !process.env.SKIP_SIGN && !sign) {
|
||||
throw new Error(
|
||||
'Windows signing needs WINDOWS_SIGNTOOL_PATH, WINDOWS_SIGN_DLIB and WINDOWS_SIGN_METADATA; set SKIP_SIGN=1 for an unsigned build.',
|
||||
);
|
||||
}
|
||||
},
|
||||
preMake: async () => ensure7zip(),
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
|
||||
function windowsSign() {
|
||||
if (process.platform !== 'win32' || process.env.SKIP_SIGN) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const {
|
||||
WINDOWS_SIGNTOOL_PATH: signToolPath,
|
||||
WINDOWS_SIGN_DLIB: dlib,
|
||||
WINDOWS_SIGN_METADATA: metadata
|
||||
} = process.env;
|
||||
|
||||
if (!signToolPath || !dlib || !metadata) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
signToolPath,
|
||||
automaticallySelectCertificate: false,
|
||||
signWithParams: ['/dlib', dlib, '/dmdf', metadata],
|
||||
timestampServer: 'http://timestamp.acs.microsoft.com',
|
||||
hashes: ['sha256'],
|
||||
} as unknown as MakerSquirrelConfig;
|
||||
}
|
||||
|
||||
function ensure7zip() {
|
||||
if (process.platform !== 'win32') return;
|
||||
const require = createRequire(__filename);
|
||||
const winstaller = require.resolve('electron-winstaller/package.json', {
|
||||
paths: [dirname(require.resolve('@electron-forge/maker-squirrel/package.json'))],
|
||||
});
|
||||
const vendor = join(dirname(winstaller), 'vendor');
|
||||
for (const ext of ['exe', 'dll']) {
|
||||
const target = join(vendor, `7z.${ext}`);
|
||||
if (!existsSync(target)) copyFileSync(join(vendor, `7z-${arch()}.${ext}`), target);
|
||||
}
|
||||
}
|
||||
|
||||
export default config;
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@diffusionstudio/desktop",
|
||||
"private": true,
|
||||
"version": "0.216.0",
|
||||
"version": "0.205.0",
|
||||
"license": "MPL-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@ -10,7 +10,7 @@
|
||||
"main": "dist/main.js",
|
||||
"scripts": {
|
||||
"build:preload": "esbuild src/preload.ts --bundle --platform=node --format=cjs --external:electron --outfile=dist/preload.js",
|
||||
"build:main": "esbuild src/main.ts --bundle --platform=node --format=cjs --loader:.png=binary --external:electron --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/main.js",
|
||||
"build:main": "esbuild src/main.ts --bundle --platform=node --format=cjs --external:electron --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --outfile=dist/main.js",
|
||||
"build:native": "node scripts/build-native.mjs",
|
||||
"build": "npm run check && npm run build:main && npm run build:preload && npm run build:agent-host && npm run build:native",
|
||||
"build:web": "npm --prefix ../web run build:desktop",
|
||||
@ -24,15 +24,11 @@
|
||||
"publish": "npm run build && npm run build:web && npm run stage:cli && npm run stage:runtime && npm run stage:docs && electron-forge publish",
|
||||
"make:icns": "sh scripts/make-icns.sh",
|
||||
"test": "vitest run",
|
||||
"build:agent-host": "esbuild ../../packages/agent-chat/src/bin.ts --bundle --platform=node --format=esm --target=node20 --external:electron \"--external:@anthropic-ai/claude-agent-sdk-*\" --banner:js=\"import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);\" --outfile=dist/agent-host.mjs",
|
||||
"make:ico": "python3 scripts/win-assets.py ico",
|
||||
"make:spinner": "python3 scripts/win-assets.py spinner",
|
||||
"make:tray-menu": "sh scripts/tray-menu-icons.sh"
|
||||
"build:agent-host": "esbuild ../../packages/agent-chat/src/bin.ts --bundle --platform=node --format=esm --target=node20 --external:electron '--external:@anthropic-ai/claude-agent-sdk-*' --banner:js=\"import { createRequire as __createRequire } from 'node:module'; const require = __createRequire(import.meta.url);\" --outfile=dist/agent-host.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@electron-forge/cli": "^7.11.1",
|
||||
"@electron-forge/maker-dmg": "^7.11.1",
|
||||
"@electron-forge/maker-squirrel": "^7.11.2",
|
||||
"@electron-forge/maker-zip": "^7.11.1",
|
||||
"@electron-forge/publisher-github": "^7.11.1",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
@ -44,7 +40,6 @@
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.29.7",
|
||||
"@babel/preset-typescript": "^7.27.1",
|
||||
"@diffusionstudio/agent-chat": "*",
|
||||
"@diffusionstudio/dapi": "*",
|
||||
"@diffusionstudio/jsx": "*",
|
||||
"@modelcontextprotocol/sdk": "^1.30.0",
|
||||
@ -53,6 +48,7 @@
|
||||
"nanoid": "^6.0.1",
|
||||
"ts-morph": "^28.0.0",
|
||||
"update-electron-app": "^3.0.0",
|
||||
"yaml": "^2.9.0"
|
||||
"yaml": "^2.9.0",
|
||||
"@diffusionstudio/agent-chat": "*"
|
||||
}
|
||||
}
|
||||
|
||||
@ -5,16 +5,9 @@
|
||||
// Stages the dapi CLI into apps/desktop/cli so electron-forge can ship it as
|
||||
// an app resource (Contents/Resources/cli). The staged layout:
|
||||
// cli/dapi.js bundled CLI (built by apps/cli), self-contained
|
||||
// cli/bin/dapi macOS shell wrapper: what Claude Desktop runs as
|
||||
// `dapi mcp` (registered by mcp-install.ts) and the file
|
||||
// that gets linked into PATH
|
||||
// cli/bin/dapi.cmd Windows wrapper, relative to the install folder. PATH
|
||||
// and the agents get a shim outside the install folder
|
||||
// instead (src/cli-windows.ts), since Squirrel moves the
|
||||
// app on every update; this one is for running the CLI
|
||||
// straight out of an install.
|
||||
// Each host stages its own wrapper; `--all` stages both, so a macOS host can
|
||||
// produce a Windows tree for inspection.
|
||||
// cli/bin/dapi shell wrapper: what Claude Desktop runs as `dapi mcp`
|
||||
// (registered by mcp-install.ts) and the file that gets
|
||||
// linked into PATH
|
||||
|
||||
import { chmodSync, cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
@ -32,8 +25,6 @@ cpSync(join(cliDir, "dist", "index.js"), join(stageDir, "dapi.js"));
|
||||
// The wrapper runs the CLI bundle on the app's own Electron binary in Node
|
||||
// mode, so users need no separate Node install. It resolves symlinks first
|
||||
// because both Homebrew and the in-app installer link it into PATH.
|
||||
const all = process.argv.includes("--all");
|
||||
|
||||
const wrapper = `#!/bin/sh
|
||||
SELF="$0"
|
||||
while [ -L "$SELF" ]; do
|
||||
@ -47,23 +38,7 @@ DIR="$(cd "$(dirname "$SELF")" && pwd)"
|
||||
export DIFFUSION_APP_PATH="$(cd "$DIR/../../../.." && pwd)"
|
||||
ELECTRON_RUN_AS_NODE=1 exec "$DIR/../../../MacOS/Diffusion Studio" "$DIR/../dapi.js" "$@"
|
||||
`;
|
||||
|
||||
if (all || process.platform !== "win32") {
|
||||
writeFileSync(join(stageDir, "bin", "dapi"), wrapper);
|
||||
chmodSync(join(stageDir, "bin", "dapi"), 0o755);
|
||||
}
|
||||
|
||||
// Staged at <install>\resources\cli\bin, three folders below the executable.
|
||||
const cmdWrapper = [
|
||||
"@echo off",
|
||||
"setlocal",
|
||||
'set "ELECTRON_RUN_AS_NODE=1"',
|
||||
'"%~dp0..\\..\\..\\Diffusion Studio.exe" "%~dp0..\\dapi.js" %*',
|
||||
"",
|
||||
].join("\r\n");
|
||||
|
||||
if (all || process.platform === "win32") {
|
||||
writeFileSync(join(stageDir, "bin", "dapi.cmd"), cmdWrapper);
|
||||
}
|
||||
writeFileSync(join(stageDir, "bin", "dapi"), wrapper);
|
||||
chmodSync(join(stageDir, "bin", "dapi"), 0o755);
|
||||
|
||||
console.log(`stage-cli: staged dapi at ${stageDir}`);
|
||||
|
||||
@ -19,7 +19,6 @@ import { createRequire } from "node:module";
|
||||
import { existsSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, closeSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { npm } from "../../../scripts/lib/npm.mjs";
|
||||
|
||||
const desktopDir = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const stageDir = join(desktopDir, "runtime");
|
||||
@ -45,7 +44,10 @@ writeFileSync(
|
||||
JSON.stringify({ name: "desktop-runtime", private: true, dependencies }, null, 2),
|
||||
);
|
||||
|
||||
npm(["install", "--omit=dev", "--no-audit", "--no-fund", "--no-package-lock"], { cwd: stageDir });
|
||||
execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund", "--no-package-lock"], {
|
||||
cwd: stageDir,
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
// Mach-O files inside Resources are not reached by the app-bundle signing
|
||||
// pass, and notarization rejects unsigned executables; sign them here.
|
||||
|
||||
@ -1,15 +0,0 @@
|
||||
#!/bin/sh
|
||||
# Regenerates the Windows tray menu icons: assets/tray/menu/<name>.svg ->
|
||||
# <name>.png (16px) and <name>@2x.png (32px). Black on transparent; the app
|
||||
# recolors them to match the menu's light or dark theme. macOS uses SF
|
||||
# Symbols instead and does not need these.
|
||||
#
|
||||
# Needs rsvg-convert (brew install librsvg).
|
||||
|
||||
set -e
|
||||
cd "$(dirname "$0")/../assets/tray/menu"
|
||||
for svg in *.svg; do
|
||||
name="${svg%.svg}"
|
||||
rsvg-convert -w 16 -h 16 "$svg" -o "$name.png"
|
||||
rsvg-convert -w 32 -h 32 "$svg" -o "$name@2x.png"
|
||||
done
|
||||
@ -1,178 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# Regenerates the Windows-only assets:
|
||||
#
|
||||
# python3 scripts/win-assets.py ico -> assets/icon.ico
|
||||
# python3 scripts/win-assets.py spinner -> assets/install-spinner.gif
|
||||
# python3 scripts/win-assets.py -> both
|
||||
#
|
||||
# Source is assets/icon-win.png (1024x1024). Unlike the macOS icon it fills
|
||||
# the canvas with no margin and no drop shadow, which is what Windows expects.
|
||||
#
|
||||
# Needs Pillow (pip install pillow) and, for the spinner, Geist Medium; set
|
||||
# WIN_ASSETS_FONT to its path if it is not in ~/Library/Fonts.
|
||||
#
|
||||
# icon.ico carries every size Windows asks for at 100-200% scaling. 40px and
|
||||
# up are Lanczos downscales of the source; 32px and below are drawn from
|
||||
# scratch (flat red rounded square, white hexagon ring) because a downscaled
|
||||
# glossy icon turns to mush at taskbar size. All entries are 32-bit BGRA with
|
||||
# an alpha channel; the 256px one is PNG-compressed as Vista+ allows.
|
||||
#
|
||||
# install-spinner.gif is Squirrel's whole install UI: shown 1:1 in a
|
||||
# borderless window until the app launches. White background, icon,
|
||||
# one label, one indeterminate bar in the app's primary blue.
|
||||
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
|
||||
ASSETS = os.path.join(ROOT, 'assets')
|
||||
SOURCE = os.path.join(ASSETS, 'icon-win.png')
|
||||
|
||||
RED = (255, 25, 52)
|
||||
BLUE = (0, 140, 255) # --primary in apps/web/src/index.css, hsla(207, 100%, 50%)
|
||||
WHITE = (255, 255, 255)
|
||||
BACKGROUND = (255, 255, 255)
|
||||
TEXT = (22, 22, 24)
|
||||
TRACK = (224, 224, 224)
|
||||
|
||||
|
||||
def source():
|
||||
im = Image.open(SOURCE).convert('RGBA')
|
||||
if im.size != (1024, 1024):
|
||||
sys.exit(f'{SOURCE} must be 1024x1024, got {im.size}')
|
||||
return im
|
||||
|
||||
|
||||
# --- icon.ico ---------------------------------------------------------------
|
||||
|
||||
ICO_SIZES = [256, 128, 96, 64, 48, 40, 32, 24, 20, 16]
|
||||
|
||||
|
||||
def drawn_frame(size):
|
||||
ss = 16
|
||||
w = size * ss
|
||||
im = Image.new('RGBA', (w, w), (0, 0, 0, 0))
|
||||
d = ImageDraw.Draw(im)
|
||||
d.rounded_rectangle((0, 0, w - 1, w - 1), radius=0.22 * size * ss, fill=RED + (255,))
|
||||
stroke = max(2, round(0.10 * size * 2) / 2) * ss
|
||||
radius = (0.38 * size - stroke / ss / 2) * ss
|
||||
c = w / 2
|
||||
pts = [
|
||||
(c + radius * math.sin(math.radians(60 * i)), c - radius * math.cos(math.radians(60 * i)))
|
||||
for i in range(6)
|
||||
]
|
||||
d.line(pts + [pts[0], pts[1]], fill=WHITE + (255,), width=int(stroke), joint='curve')
|
||||
for x, y in pts:
|
||||
d.ellipse((x - stroke / 2, y - stroke / 2, x + stroke / 2, y + stroke / 2), fill=WHITE + (255,))
|
||||
return im.resize((size, size), Image.LANCZOS)
|
||||
|
||||
|
||||
def scaled_frame(src, size):
|
||||
im = src.resize((size, size), Image.LANCZOS)
|
||||
if size <= 128:
|
||||
im = im.filter(ImageFilter.UnsharpMask(radius=0.6, percent=50, threshold=0))
|
||||
return im
|
||||
|
||||
|
||||
def dib(im):
|
||||
w, h = im.size
|
||||
px = im.load()
|
||||
rows = b''.join(
|
||||
bytes(b for x in range(w) for b in (px[x, y][2], px[x, y][1], px[x, y][0], px[x, y][3]))
|
||||
for y in range(h - 1, -1, -1)
|
||||
)
|
||||
stride = ((w + 31) // 32) * 4
|
||||
mask = bytes(stride * h) # AND mask all-visible; alpha carries transparency
|
||||
header = struct.pack('<IiiHHIIiiII', 40, w, h * 2, 1, 32, 0, len(rows) + len(mask), 2835, 2835, 0, 0)
|
||||
return header + rows + mask
|
||||
|
||||
|
||||
def make_ico():
|
||||
src = source()
|
||||
blobs = []
|
||||
for size in ICO_SIZES:
|
||||
frame = drawn_frame(size) if size <= 32 else scaled_frame(src, size)
|
||||
if size == 256:
|
||||
buf = io.BytesIO()
|
||||
frame.save(buf, 'PNG', optimize=True)
|
||||
blobs.append(buf.getvalue())
|
||||
else:
|
||||
blobs.append(dib(frame))
|
||||
out = struct.pack('<HHH', 0, 1, len(ICO_SIZES))
|
||||
offset = 6 + 16 * len(ICO_SIZES)
|
||||
entries = b''
|
||||
for size, blob in zip(ICO_SIZES, blobs):
|
||||
entries += struct.pack('<BBBBHHII', size % 256, size % 256, 0, 0, 1, 32, len(blob), offset)
|
||||
offset += len(blob)
|
||||
path = os.path.join(ASSETS, 'icon.ico')
|
||||
with open(path, 'wb') as f:
|
||||
f.write(out + entries + b''.join(blobs))
|
||||
print(f'wrote {os.path.relpath(path, ROOT)}')
|
||||
|
||||
|
||||
# --- install-spinner.gif ----------------------------------------------------
|
||||
|
||||
W, H = 440, 280
|
||||
FPS, SECONDS = 20, 2.4
|
||||
LABEL = 'Installing Diffusion Studio'
|
||||
|
||||
|
||||
def font():
|
||||
path = os.environ.get('WIN_ASSETS_FONT') or os.path.expanduser('~/Library/Fonts/Geist-Medium.ttf')
|
||||
if not os.path.exists(path):
|
||||
sys.exit(f'Geist Medium not found at {path}; set WIN_ASSETS_FONT')
|
||||
return ImageFont.truetype(path, 15)
|
||||
|
||||
|
||||
def make_spinner():
|
||||
icon = source().resize((88, 88), Image.LANCZOS)
|
||||
label_font = font()
|
||||
n = int(FPS * SECONDS)
|
||||
track_w, track_h, bar_w = 200, 4, 70
|
||||
tx, ty = (W - track_w) // 2, 214
|
||||
frames = []
|
||||
for i in range(n):
|
||||
im = Image.new('RGB', (W, H), BACKGROUND)
|
||||
d = ImageDraw.Draw(im)
|
||||
im.paste(icon, ((W - 88) // 2, 58), icon)
|
||||
tw = d.textlength(LABEL, font=label_font)
|
||||
d.text((round((W - tw) / 2), 166), LABEL, font=label_font, fill=TEXT)
|
||||
d.rounded_rectangle((tx, ty, tx + track_w, ty + track_h), radius=2, fill=TRACK)
|
||||
p = 0.5 - 0.5 * math.cos(math.pi * i / n) # ease in-out, one sweep per loop
|
||||
x0 = tx - bar_w + p * (track_w + bar_w)
|
||||
a, b = max(tx, x0), min(tx + track_w, x0 + bar_w)
|
||||
if b - a >= 6:
|
||||
d.rounded_rectangle((a, ty, b, ty + track_h), radius=2, fill=BLUE)
|
||||
frames.append(im)
|
||||
# One shared palette so nothing flickers between frames, taken from a
|
||||
# mid-loop frame where the bar is fully on the track so its colour is kept.
|
||||
palette = frames[n // 2].quantize(colors=128, method=Image.Quantize.MEDIANCUT)
|
||||
quantized = [f.quantize(palette=palette, dither=Image.Dither.NONE) for f in frames]
|
||||
# Median cut averages the background with the icon's antialiased fringe;
|
||||
# pin the slot every background pixel landed in to the exact colour.
|
||||
for q in quantized:
|
||||
entries = list(q.getpalette())
|
||||
slot = q.getpixel((0, 0))
|
||||
entries[slot * 3:slot * 3 + 3] = BACKGROUND
|
||||
q.putpalette(entries)
|
||||
path = os.path.join(ASSETS, 'install-spinner.gif')
|
||||
quantized[0].save(
|
||||
path,
|
||||
save_all=True,
|
||||
append_images=quantized[1:],
|
||||
duration=int(1000 / FPS),
|
||||
loop=0,
|
||||
optimize=False,
|
||||
)
|
||||
print(f'wrote {os.path.relpath(path, ROOT)}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
what = sys.argv[1:] or ['ico', 'spinner']
|
||||
for target in what:
|
||||
{'ico': make_ico, 'spinner': make_spinner}[target]()
|
||||
@ -2,6 +2,12 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The agent chat host as a utility process: forked from the ESM bundle
|
||||
// esbuild puts in dist/, configured over parentPort (never argv, which
|
||||
// every process can read), restarted with backoff when it dies. The
|
||||
// renderer asks for the endpoint over the existing IPC and talks to the
|
||||
// host over its own WebSocket from there.
|
||||
|
||||
import { app, utilityProcess } from "electron";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
@ -13,8 +19,6 @@ type AgentChatOptions = { dataDir: string; mcpUrl: string | null; version: strin
|
||||
const DEV_ORIGIN = "http://localhost:5173";
|
||||
const RESTART_DELAYS_MS = [1000, 2000, 5000, 10_000];
|
||||
const STOP_GRACE_MS = 3000;
|
||||
// How long an ask for the endpoint waits for a host it had to start.
|
||||
const START_WAIT_MS = 10_000;
|
||||
|
||||
let child: UtilityProcess | null = null;
|
||||
let endpoint: { url: string } | null = null;
|
||||
@ -24,8 +28,6 @@ let restarts = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let stopped = false;
|
||||
|
||||
const waiting = new Set<() => void>();
|
||||
|
||||
function spawn(): void {
|
||||
if (!options || stopped) return;
|
||||
const path = join(app.getAppPath(), "dist", "agent-host.mjs");
|
||||
@ -49,9 +51,6 @@ function spawn(): void {
|
||||
if (message?.type === "listening" && typeof message.url === "string") {
|
||||
endpoint = { url: message.url };
|
||||
restarts = 0;
|
||||
for (const wake of [...waiting]) {
|
||||
wake();
|
||||
}
|
||||
console.log(`[agent-chat] host listening at ${message.url.replace(/token=.*$/, "token=…")}`);
|
||||
} else if (message?.type === "error") {
|
||||
console.error(`[agent-chat] host failed to start: ${message.message}`);
|
||||
@ -73,43 +72,23 @@ function spawn(): void {
|
||||
});
|
||||
}
|
||||
|
||||
/** Generates the token; the host is forked when it is first needed. Call once, after `whenReady`. */
|
||||
export function configureAgentChat(next: AgentChatOptions): void {
|
||||
/** Generates the token and forks the host. Call once, after `whenReady`. */
|
||||
export function startAgentChat(next: AgentChatOptions): void {
|
||||
options = next;
|
||||
token = randomBytes(32).toString("base64url");
|
||||
stopped = false;
|
||||
restarts = 0;
|
||||
spawn();
|
||||
}
|
||||
|
||||
/** Where the host is listening, starting it when it is not running; null when it does not come up in time. */
|
||||
export function agentChatEndpoint(): Promise<{ url: string } | null> {
|
||||
if (endpoint || stopped || !options) {
|
||||
return Promise.resolve(endpoint);
|
||||
}
|
||||
// Not running and not about to restart: this is the first ask.
|
||||
if (!child && !restartTimer) {
|
||||
spawn();
|
||||
}
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const wake = () => {
|
||||
clearTimeout(timer);
|
||||
waiting.delete(wake);
|
||||
resolve(endpoint);
|
||||
};
|
||||
const timer = setTimeout(wake, START_WAIT_MS);
|
||||
waiting.add(wake);
|
||||
});
|
||||
/** Where the host is right now: null while it is (re)starting. */
|
||||
export function agentChatEndpoint(): { url: string } | null {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
/** Best effort: a host that does not come up leaves the chats behind. They aren't trashed with the folder. */
|
||||
export async function deleteProjectChats(projectId: string): Promise<void> {
|
||||
if (!projectId) return;
|
||||
const running = await agentChatEndpoint();
|
||||
|
||||
if (running) {
|
||||
child?.postMessage({ type: "deleteProject", projectId });
|
||||
}
|
||||
/** Best effort: a host that is down or restarting leaves the chats behind. They aren't trashed with the folder. */
|
||||
export function deleteProjectChats(projectId: string): void {
|
||||
if (projectId && endpoint) child?.postMessage({ type: "deleteProject", projectId });
|
||||
}
|
||||
|
||||
/** Asks the host to stop (it kills its harness trees), then kills it after a grace period. */
|
||||
|
||||
@ -3,107 +3,69 @@
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { app } from "electron";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { stat, writeFile } from "node:fs/promises";
|
||||
|
||||
import type { ClientEventName, TrackedEvent, TrackProps } from "@diffusionstudio/api-contract";
|
||||
import type { WindowHost } from "./window-host";
|
||||
|
||||
const enabled = app.isPackaged || process.env.DIFFUSION_ANALYTICS === "1";
|
||||
|
||||
const FLUSH_INTERVAL_MS = 30_000;
|
||||
const BATCH_MAX = 100;
|
||||
const QUEUE_MAX = 2_000;
|
||||
|
||||
const queue: TrackedEvent[] = [];
|
||||
|
||||
let apiUrl: string | null = null;
|
||||
let token: string | null | undefined;
|
||||
|
||||
/** Canvas edits by kind, and source files changed from outside the app, since the last flush. */
|
||||
let canvasEdits: Record<string, number> = {};
|
||||
let changedFiles = new Set<string>();
|
||||
|
||||
export function configureAnalytics(config: { apiUrl: string; token: string | null }): void {
|
||||
apiUrl = config.apiUrl;
|
||||
token = config.token;
|
||||
}
|
||||
|
||||
export function track(name: ClientEventName, props: TrackProps = {}): void {
|
||||
if (!enabled) return;
|
||||
// Undefined values would fail validation; JSON leaves them out.
|
||||
queue.push({
|
||||
id: randomUUID(),
|
||||
at: new Date().toISOString(),
|
||||
name,
|
||||
props: JSON.parse(JSON.stringify(props)),
|
||||
});
|
||||
|
||||
if (queue.length > QUEUE_MAX) {
|
||||
queue.splice(0, queue.length - QUEUE_MAX);
|
||||
}
|
||||
}
|
||||
|
||||
/** Edits the canvas wrote back to the source (move, insert, remove, …). */
|
||||
export function countCanvasEdits(kinds: string[]): void {
|
||||
for (const kind of kinds) {
|
||||
canvasEdits[kind] = (canvasEdits[kind] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/** A source file changed from outside the app: an agent or an editor writing code. */
|
||||
export function countCodeChange(path: string): void {
|
||||
changedFiles.add(path);
|
||||
}
|
||||
import { access, writeFile } from "node:fs/promises";
|
||||
|
||||
/**
|
||||
* Starts the flush and usage timers and records the launch. The first launch of an
|
||||
* install is recorded once, guarded by a marker file in `userData`; its age
|
||||
* goes on every `app_opened`, so install-to-sign-up time needs no device id.
|
||||
* Install tracking, proxied by the first launch of a packaged build. The
|
||||
* renderer's Umami script never fires inside Electron (its `data-domains`
|
||||
* gate does not match the `file://` origin), so main posts one event
|
||||
* directly to Umami's send API and drops a marker file in `userData` to
|
||||
* never send it again. Offline first launches retry on the next launch.
|
||||
*/
|
||||
export async function startAnalytics(windows: WindowHost): Promise<void> {
|
||||
if (!enabled) return;
|
||||
|
||||
setInterval(flush, FLUSH_INTERVAL_MS);
|
||||
setInterval(() => (windows.current() && track("app_used")), 60_000);
|
||||
const UMAMI_ENDPOINT = "https://cloud.umami.is/api/send";
|
||||
const UMAMI_WEBSITE_ID = "e898e381-6ce3-4f5f-a485-8327ec9aa88b";
|
||||
const HOSTNAME = "desktop.diffusion.studio";
|
||||
const MARKER_FILE = "install-tracked";
|
||||
|
||||
const marker = join(app.getPath("userData"), "install-tracked");
|
||||
const installedAt = await stat(marker).then((info) => info.birthtimeMs, () => null);
|
||||
|
||||
if (installedAt === null) {
|
||||
track("app_installed", { arch: process.arch });
|
||||
await writeFile(marker, new Date().toISOString()).catch(() => { });
|
||||
}
|
||||
|
||||
track("app_opened", { install_age_s: Math.round((Date.now() - (installedAt ?? Date.now())) / 1000) });
|
||||
// Umami discards events whose User-Agent trips its bot filter, which both
|
||||
// Node's fetch default and Electron's own UA do — send a plain browser UA
|
||||
// that still attributes the right OS.
|
||||
function userAgent(): string {
|
||||
const platform =
|
||||
process.platform === "darwin"
|
||||
? "Macintosh; Intel Mac OS X 10_15_7"
|
||||
: process.platform === "win32"
|
||||
? "Windows NT 10.0; Win64; x64"
|
||||
: "X11; Linux x86_64";
|
||||
return `Mozilla/5.0 (${platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`;
|
||||
}
|
||||
|
||||
async function flush(): Promise<void> {
|
||||
const edits = Object.values(canvasEdits).reduce((sum, n) => sum + n, 0);
|
||||
if (edits) {
|
||||
track("canvas_edited", { edits, ...canvasEdits });
|
||||
}
|
||||
if (changedFiles.size) {
|
||||
track("code_changed", { files: changedFiles.size });
|
||||
}
|
||||
canvasEdits = {};
|
||||
changedFiles = new Set();
|
||||
export async function trackInstall(): Promise<void> {
|
||||
if (!app.isPackaged) return;
|
||||
|
||||
if (!queue.length || !apiUrl || token === undefined) return;
|
||||
const batch = queue.splice(0, BATCH_MAX);
|
||||
const marker = join(app.getPath("userData"), MARKER_FILE);
|
||||
try {
|
||||
const response = await fetch(`${apiUrl}/api/v2/trpc/events.track`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify({ source: "desktop", appVersion: app.getVersion(), platform: process.platform, events: batch }),
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
// Sent, or a batch the API will never take (400): either way it is done.
|
||||
if (response.ok || response.status === 400) return;
|
||||
await access(marker);
|
||||
return;
|
||||
} catch {
|
||||
// Offline or the API unreachable.
|
||||
// No marker yet — this is the first (tracked) launch.
|
||||
}
|
||||
|
||||
queue.unshift(...batch);
|
||||
try {
|
||||
const response = await fetch(UMAMI_ENDPOINT, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "User-Agent": userAgent() },
|
||||
body: JSON.stringify({
|
||||
type: "event",
|
||||
payload: {
|
||||
website: UMAMI_WEBSITE_ID,
|
||||
hostname: HOSTNAME,
|
||||
url: "/desktop/install",
|
||||
name: "desktop_install",
|
||||
data: {
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
version: app.getVersion(),
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
if (response.ok) {
|
||||
await writeFile(marker, new Date().toISOString());
|
||||
}
|
||||
} catch {
|
||||
// Offline or Umami unreachable — retried on the next launch.
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,27 +2,23 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The `dapi` command on PATH: a symlink from /usr/local/bin to the wrapper
|
||||
// the app ships in its resources. Creating it needs an admin password,
|
||||
// which macOS asks for through osascript so the app itself never sees
|
||||
// credentials; removing a link asks only when the folder demands it.
|
||||
|
||||
import { app } from "electron";
|
||||
import { execFile } from "node:child_process";
|
||||
import { existsSync, lstatSync, unlinkSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { addShimToPath, removeShimFromPath, shimOnPath, shimPath, writeShim } from "./cli-windows";
|
||||
|
||||
import type { CliInstallResult, CliStatus, CliUninstallResult } from "./main-channels";
|
||||
|
||||
export const CLI_LINK_DIR = "/usr/local/bin";
|
||||
export const CLI_LINK_PATH = "/usr/local/bin/dapi";
|
||||
|
||||
// The dev workflow links the workspace build into Homebrew's bin instead
|
||||
// (`npm run link` in apps/cli), so that location counts as installed too.
|
||||
const DEV_LINK_DIR = "/opt/homebrew/bin";
|
||||
|
||||
// `diffusion` is what we point to first when reporting status; `dapi` rides
|
||||
// alongside it as an alias, and is also what an install from before this
|
||||
// pair existed left behind.
|
||||
const LINK_NAMES = ["diffusion", "dapi"] as const;
|
||||
|
||||
const linkPaths = (dir: string): string[] => LINK_NAMES.map((name) => `${dir}/${name}`);
|
||||
// (`symlink:create` in apps/cli), so that location counts as installed too.
|
||||
const DEV_LINK_PATH = "/opt/homebrew/bin/dapi";
|
||||
|
||||
/**
|
||||
* Whether `path` is a symlink — dangling or not, since a link left behind
|
||||
@ -33,51 +29,21 @@ function isLink(path: string): boolean {
|
||||
return lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink() ?? false;
|
||||
}
|
||||
|
||||
/** The first of the two locations that holds any of our links, or null. */
|
||||
function installedDir(): string | null {
|
||||
for (const dir of [CLI_LINK_DIR, DEV_LINK_DIR]) {
|
||||
if (linkPaths(dir).some((path) => isLink(path) || existsSync(path))) {
|
||||
return dir;
|
||||
}
|
||||
/** The first of the two locations that holds anything, or null. */
|
||||
function installedPath(): string | null {
|
||||
for (const path of [CLI_LINK_PATH, DEV_LINK_PATH]) {
|
||||
if (isLink(path) || existsSync(path)) return path;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrites the Windows shim so it names this executable. Runs on every
|
||||
* packaged launch, because an update moved the app to a new folder; the
|
||||
* agents' MCP entries point at the shim whether or not it is on PATH.
|
||||
*/
|
||||
export function refreshCliShim(): void {
|
||||
if (process.platform !== "win32" || !app.isPackaged) return;
|
||||
writeShim().catch((e) => console.error("cli shim: could not write", e));
|
||||
}
|
||||
|
||||
async function cliStatusWin32(): Promise<CliStatus> {
|
||||
const installed = await shimOnPath().catch(() => false);
|
||||
if (installed) {
|
||||
return { installed: true, path: shimPath(), managed: true, available: true };
|
||||
}
|
||||
/** Where `dapi` stands on this machine, without asking for a password. */
|
||||
export function cliStatus(): CliStatus {
|
||||
const path = installedPath();
|
||||
if (path) return { installed: true, path, managed: isLink(path), available: true };
|
||||
return { installed: false, path: null, managed: false, available: app.isPackaged };
|
||||
}
|
||||
|
||||
async function cliStatusDarwin(): Promise<CliStatus> {
|
||||
const dir = installedDir();
|
||||
if (dir) {
|
||||
const path = linkPaths(dir).find((candidate) => isLink(candidate) || existsSync(candidate))!;
|
||||
return { installed: true, path, managed: isLink(path), available: true };
|
||||
}
|
||||
return { installed: false, path: null, managed: false, available: app.isPackaged };
|
||||
}
|
||||
|
||||
/** Where `diffusion` (or its `dapi` alias) stands on this machine, without asking for a password. */
|
||||
export async function cliStatus(): Promise<CliStatus> {
|
||||
if (process.platform === "win32") return cliStatusWin32();
|
||||
if (process.platform === "darwin") return cliStatusDarwin();
|
||||
|
||||
return { installed: false, path: null, managed: false, available: false };
|
||||
}
|
||||
|
||||
// The standard macOS admin prompt, for the one shell line that needs it.
|
||||
function elevated(shell: string): Promise<void> {
|
||||
const script = `do shell script "${shell.replaceAll('"', '\\"')}" with administrator privileges`;
|
||||
@ -89,88 +55,45 @@ function elevated(shell: string): Promise<void> {
|
||||
/** osascript error -128: the user dismissed the prompt. Not an error, not done. */
|
||||
const cancelled = (e: unknown): boolean => ((e as Error).message ?? "").includes("-128");
|
||||
|
||||
async function installCliDarwin(): Promise<CliInstallResult> {
|
||||
export async function installCli(): Promise<CliInstallResult> {
|
||||
if (!app.isPackaged) {
|
||||
return {
|
||||
status: "error",
|
||||
error: "Installing the CLI is only available in the packaged app. Use `npm run symlink:create` in development.",
|
||||
};
|
||||
}
|
||||
const wrapper = join(process.resourcesPath, "cli", "bin", "dapi");
|
||||
const links = linkPaths(CLI_LINK_DIR).map((path) => `ln -sf '${wrapper}' '${path}'`).join(" && ");
|
||||
try {
|
||||
await elevated(`mkdir -p ${CLI_LINK_DIR} && ${links}`);
|
||||
await elevated(`mkdir -p /usr/local/bin && ln -sf '${wrapper}' '${CLI_LINK_PATH}'`);
|
||||
return { status: "installed" };
|
||||
} catch (e) {
|
||||
return cancelled(e) ? { status: "cancelled" } : { status: "error", error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
async function installCliWin32(): Promise<CliInstallResult> {
|
||||
try {
|
||||
await writeShim();
|
||||
await addShimToPath();
|
||||
return { status: "installed" };
|
||||
} catch (e) {
|
||||
return { status: "error", error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
export async function installCli(): Promise<CliInstallResult> {
|
||||
if (!app.isPackaged) {
|
||||
return {
|
||||
status: "error",
|
||||
error: `Installing the CLI is only available in the packaged app. Use \`npm run link\` in apps/cli in development.`,
|
||||
};
|
||||
}
|
||||
if (process.platform === "win32") return installCliWin32();
|
||||
if (process.platform === "darwin") return installCliDarwin();
|
||||
|
||||
return {
|
||||
status: "error",
|
||||
error: `Installing the CLI is only available on Windows and macOS.`,
|
||||
};
|
||||
}
|
||||
|
||||
async function uninstallCliWin32(): Promise<CliUninstallResult> {
|
||||
try {
|
||||
if (!(await shimOnPath())) return { status: "absent" };
|
||||
await removeShimFromPath();
|
||||
return { status: "removed" };
|
||||
} catch (e) {
|
||||
return { status: "error", error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
async function uninstallCliDarwin(): Promise<CliUninstallResult> {
|
||||
const dir = installedDir();
|
||||
if (!dir) return { status: "absent" };
|
||||
const present = linkPaths(dir).filter((path) => isLink(path) || existsSync(path));
|
||||
const notLinks = present.filter((path) => !isLink(path));
|
||||
if (notLinks.length > 0) {
|
||||
const is = notLinks.length > 1 ? "are not links" : "is not a link";
|
||||
return { status: "error", error: `${notLinks.join(", ")} ${is}, so nothing was removed.` };
|
||||
/**
|
||||
* Takes the `dapi` link off PATH, whichever of the two locations holds it.
|
||||
* Only a symlink is touched: a real binary somebody put there is not ours
|
||||
* to delete. The plain unlink covers Homebrew's user-owned bin; when the
|
||||
* folder refuses (/usr/local/bin is root's), the admin prompt takes over.
|
||||
*/
|
||||
export async function uninstallCli(): Promise<CliUninstallResult> {
|
||||
const path = installedPath();
|
||||
if (!path) return { status: "absent" };
|
||||
if (!isLink(path)) {
|
||||
return { status: "error", error: `${path} is not a link, so it was left alone.` };
|
||||
}
|
||||
try {
|
||||
for (const path of present) unlinkSync(path);
|
||||
unlinkSync(path);
|
||||
return { status: "removed" };
|
||||
} catch (e) {
|
||||
const code = (e as NodeJS.ErrnoException).code;
|
||||
if (code !== "EACCES" && code !== "EPERM") return { status: "error", error: (e as Error).message };
|
||||
}
|
||||
try {
|
||||
await elevated(`rm -f ${present.map((path) => `'${path}'`).join(" ")}`);
|
||||
await elevated(`rm -f '${path}'`);
|
||||
return { status: "removed" };
|
||||
} catch (e) {
|
||||
return cancelled(e) ? { status: "cancelled" } : { status: "error", error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Takes the `diffusion`/`dapi` links off PATH, whichever of the two
|
||||
* locations holds them.
|
||||
*/
|
||||
export async function uninstallCli(): Promise<CliUninstallResult> {
|
||||
if (process.platform === "win32") return uninstallCliWin32();
|
||||
if (process.platform === "darwin") return uninstallCliDarwin();
|
||||
|
||||
return {
|
||||
status: "error",
|
||||
error: `Uninstalling the CLI is only available on Windows and macOS.`,
|
||||
};
|
||||
}
|
||||
|
||||
@ -1,57 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The parts of the Windows CLI install that are decisions rather than system
|
||||
// calls: where the shim lives, what it says, and how the user's PATH is
|
||||
// edited without disturbing the entries around ours.
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { pathHas, pathWith, pathWithout, shimContent, shimDir, shimPath, stagedScript } from "./cli-windows";
|
||||
|
||||
const local = "C:\\Users\\me\\AppData\\Local";
|
||||
const exe = `${local}\\DiffusionStudio\\app-1.2.0\\Diffusion Studio.exe`;
|
||||
const dir = `${local}\\DiffusionStudio\\bin`;
|
||||
|
||||
describe("shim", () => {
|
||||
it("lives outside the versioned app folder", () => {
|
||||
expect(shimDir({ LOCALAPPDATA: local })).toBe(dir);
|
||||
expect(shimPath({ LOCALAPPDATA: local })).toBe(`${dir}\\dapi.cmd`);
|
||||
});
|
||||
|
||||
it("runs the staged CLI on the app's executable in Node mode", () => {
|
||||
expect(stagedScript(exe)).toBe(`${local}\\DiffusionStudio\\app-1.2.0\\resources\\cli\\dapi.js`);
|
||||
expect(shimContent(exe).split("\r\n")).toEqual([
|
||||
"@echo off",
|
||||
"setlocal",
|
||||
'set "ELECTRON_RUN_AS_NODE=1"',
|
||||
`"${exe}" "${stagedScript(exe)}" %*`,
|
||||
"",
|
||||
]);
|
||||
});
|
||||
|
||||
it("escapes percent signs, which batch files would expand", () => {
|
||||
expect(shimContent("C:\\Users\\100%me\\app.exe", "C:\\x\\dapi.js")).toContain('"C:\\Users\\100%%me\\app.exe"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("user PATH", () => {
|
||||
const path = "%USERPROFILE%\\.cargo\\bin;C:\\Tools";
|
||||
|
||||
it("appends the folder once, leaving other entries as written", () => {
|
||||
expect(pathWith(path, dir)).toBe(`${path};${dir}`);
|
||||
expect(pathWith(`${path};${dir}`, dir)).toBe(`${path};${dir}`);
|
||||
expect(pathWith("", dir)).toBe(dir);
|
||||
});
|
||||
|
||||
it("matches without case and trailing separators", () => {
|
||||
expect(pathHas(`${path};${dir.toUpperCase()}\\`, dir)).toBe(true);
|
||||
expect(pathHas(path, dir)).toBe(false);
|
||||
});
|
||||
|
||||
it("removes every spelling of the folder and nothing else", () => {
|
||||
expect(pathWithout(`${dir}\;${path};${dir.toLowerCase()}`, dir)).toBe(path);
|
||||
expect(pathWithout(path, dir)).toBe(path);
|
||||
});
|
||||
});
|
||||
@ -1,151 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The `diffusion` (and `dapi` alias) commands on Windows. Squirrel installs
|
||||
// every version into its own `app-<version>` folder, so nothing durable may
|
||||
// point at the wrapper the app ships in its resources. What goes on PATH
|
||||
// (and, for `dapi.cmd`, into the agents' MCP configs) is a pair of shims in a
|
||||
// folder that never moves:
|
||||
// %LOCALAPPDATA%\DiffusionStudio\bin\dapi.cmd
|
||||
// %LOCALAPPDATA%\DiffusionStudio\bin\diffusion.cmd
|
||||
// The app rewrites both on every packaged launch and from Squirrel's update
|
||||
// hook, so they always name the current executable. Installing the CLI is
|
||||
// then only a matter of putting that folder on the user's PATH, which needs
|
||||
// no administrator.
|
||||
//
|
||||
// Nothing here imports electron, so the Squirrel hooks can use it before the
|
||||
// app is ready and the tests can run it anywhere.
|
||||
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, rm } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { win32 } from "node:path";
|
||||
|
||||
import { writeFileAtomic } from "./atomic";
|
||||
|
||||
/** The folder that holds the shim: the one entry we add to PATH. */
|
||||
export function shimDir(env: NodeJS.ProcessEnv = process.env): string {
|
||||
const local = env.LOCALAPPDATA || win32.join(homedir(), "AppData", "Local");
|
||||
return win32.join(local, "DiffusionStudio", "bin");
|
||||
}
|
||||
|
||||
export function shimPath(env: NodeJS.ProcessEnv = process.env): string {
|
||||
return win32.join(shimDir(env), "dapi.cmd");
|
||||
}
|
||||
|
||||
// `dapi.cmd` is the one `mcp-install.ts` registers with agents, so its name
|
||||
// and behavior above stay fixed. `diffusion.cmd` rides beside it purely so
|
||||
// the name on PATH matches the one in the docs; both run the same script.
|
||||
export function shimPaths(env: NodeJS.ProcessEnv = process.env): string[] {
|
||||
return ["dapi.cmd", "diffusion.cmd"].map((name) => win32.join(shimDir(env), name));
|
||||
}
|
||||
|
||||
/** `dapi.js` as the packaged app stages it, next to `execPath`'s resources. */
|
||||
export function stagedScript(execPath: string): string {
|
||||
return win32.join(win32.dirname(execPath), "resources", "cli", "dapi.js");
|
||||
}
|
||||
|
||||
// A literal `%` would start a variable expansion inside a batch file.
|
||||
const batch = (path: string): string => path.replaceAll("%", "%%");
|
||||
|
||||
/**
|
||||
* The shim's text: the CLI bundle on the app's own Electron binary in Node
|
||||
* mode, like the macOS wrapper, but with both paths spelled out because the
|
||||
* shim does not live beside them.
|
||||
*/
|
||||
export function shimContent(execPath: string, script: string = stagedScript(execPath)): string {
|
||||
return [
|
||||
"@echo off",
|
||||
"setlocal",
|
||||
'set "ELECTRON_RUN_AS_NODE=1"',
|
||||
`"${batch(execPath)}" "${batch(script)}" %*`,
|
||||
"",
|
||||
].join("\r\n");
|
||||
}
|
||||
|
||||
/** Points the shim at `execPath`. Safe to repeat; the write lands whole. */
|
||||
export async function writeShim(execPath: string = process.execPath, script?: string): Promise<void> {
|
||||
await mkdir(shimDir(), { recursive: true });
|
||||
const content = shimContent(execPath, script);
|
||||
await Promise.all(shimPaths().map((path) => writeFileAtomic(path, content)));
|
||||
}
|
||||
|
||||
export async function removeShim(): Promise<void> {
|
||||
await rm(shimDir(), { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// PATH entries compare without case and without a trailing separator.
|
||||
const normalize = (entry: string): string => entry.trim().replace(/[\\/]+$/, "").toLowerCase();
|
||||
|
||||
const entries = (path: string): string[] => path.split(";").filter((entry) => entry.trim() !== "");
|
||||
|
||||
export function pathHas(path: string, dir: string): boolean {
|
||||
return entries(path).some((entry) => normalize(entry) === normalize(dir));
|
||||
}
|
||||
|
||||
/** `path` with `dir` appended, or unchanged when it is already there. */
|
||||
export function pathWith(path: string, dir: string): string {
|
||||
return pathHas(path, dir) ? path : [...entries(path), dir].join(";");
|
||||
}
|
||||
|
||||
/** `path` without any spelling of `dir`. */
|
||||
export function pathWithout(path: string, dir: string): string {
|
||||
return entries(path)
|
||||
.filter((entry) => normalize(entry) !== normalize(dir))
|
||||
.join(";");
|
||||
}
|
||||
|
||||
// The user PATH lives in HKCU\Environment. It is read and written through the
|
||||
// registry rather than [Environment]::Get/SetEnvironmentVariable, which would
|
||||
// expand every %VARIABLE% in the entries that are already there and store the
|
||||
// result as a plain string. `setx` is out too: it truncates at 1024
|
||||
// characters. Removing a variable that does not exist is the cheap way to
|
||||
// make .NET broadcast WM_SETTINGCHANGE, so new terminals see the change.
|
||||
// The value travels through the environment so nothing needs quoting.
|
||||
const READ_PATH = `
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment')
|
||||
[Console]::Out.Write($key.GetValue('Path', '', 'DoNotExpandEnvironmentNames'))
|
||||
`;
|
||||
|
||||
const WRITE_PATH = `
|
||||
$key = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true)
|
||||
$kind = if ($key.GetValueNames() -contains 'Path') { $key.GetValueKind('Path') } else { 'ExpandString' }
|
||||
$value = if ($env:DAPI_USER_PATH) { $env:DAPI_USER_PATH } else { '' }
|
||||
$key.SetValue('Path', $value, $kind)
|
||||
[Environment]::SetEnvironmentVariable('DAPI_PATH_BROADCAST', $null, 'User')
|
||||
`;
|
||||
|
||||
function powershell(script: string, env: NodeJS.ProcessEnv = {}): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
"powershell.exe",
|
||||
["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script],
|
||||
{ env: { ...process.env, ...env }, windowsHide: true },
|
||||
(err, stdout) => (err ? reject(err) : resolve(stdout)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export const readUserPath = (): Promise<string> => powershell(READ_PATH);
|
||||
|
||||
export async function writeUserPath(path: string): Promise<void> {
|
||||
await powershell(WRITE_PATH, { DAPI_USER_PATH: path });
|
||||
}
|
||||
|
||||
/** Whether the shim folder is on the user's PATH. */
|
||||
export async function shimOnPath(): Promise<boolean> {
|
||||
return pathHas(await readUserPath(), shimDir());
|
||||
}
|
||||
|
||||
export async function addShimToPath(): Promise<void> {
|
||||
const path = await readUserPath();
|
||||
const next = pathWith(path, shimDir());
|
||||
if (next !== path) await writeUserPath(next);
|
||||
}
|
||||
|
||||
export async function removeShimFromPath(): Promise<void> {
|
||||
const path = await readUserPath();
|
||||
const next = pathWithout(path, shimDir());
|
||||
if (next !== path) await writeUserPath(next);
|
||||
}
|
||||
@ -1,47 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The files on the system clipboard: what a copy in Finder or Explorer (or
|
||||
// of a recording in a screenshot app) leaves there. The renderer reads
|
||||
// pictures itself, but the web clipboard API knows nothing of files, and
|
||||
// outside a paste event this is the only way to them.
|
||||
|
||||
import { clipboard } from "electron";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
/** The files on the clipboard, by path, in the order they were copied. */
|
||||
export function clipboardPaths(): string[] {
|
||||
switch (process.platform) {
|
||||
case "darwin": {
|
||||
// Every file of a copy is in the filenames list, a plist of paths; the
|
||||
// file URL type only holds the first.
|
||||
const plist = clipboard.read("NSFilenamesPboardType");
|
||||
const paths = [...plist.matchAll(/<string>([^<]*)<\/string>/g)].map((match) => unescapeXml(match[1]!));
|
||||
if (paths.length) return paths;
|
||||
const url = clipboard.read("public.file-url");
|
||||
return url.startsWith("file:") ? [fileURLToPath(url)] : [];
|
||||
}
|
||||
case "win32": {
|
||||
// Only the first file of a copy: the full list is in CF_HDROP, which
|
||||
// Electron cannot read.
|
||||
const path = clipboard.readBuffer("FileNameW").toString("utf16le").split("\0")[0];
|
||||
return path ? [path] : [];
|
||||
}
|
||||
default:
|
||||
return clipboard
|
||||
.read("text/uri-list")
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => line.startsWith("file:"))
|
||||
.map((url) => fileURLToPath(url));
|
||||
}
|
||||
}
|
||||
|
||||
function unescapeXml(text: string): string {
|
||||
return text
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, "'")
|
||||
.replace(/&/g, "&");
|
||||
}
|
||||
@ -1,49 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { dropboxRoots, isUnder, windowsCloudSyncKind } from "./cloud-sync-windows";
|
||||
|
||||
const home = "C:\\Users\\me";
|
||||
|
||||
describe("isUnder", () => {
|
||||
it("compares the way Windows does: no case, whole segments", () => {
|
||||
expect(isUnder("c:\\users\\ME\\OneDrive\\Videos\\clip", "C:\\Users\\me\\OneDrive")).toBe(true);
|
||||
expect(isUnder("C:\\Users\\me\\OneDrive", "C:\\Users\\me\\OneDrive\\")).toBe(true);
|
||||
expect(isUnder("C:\\Users\\me\\OneDrive-old\\clip", "C:\\Users\\me\\OneDrive")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dropboxRoots", () => {
|
||||
it("reads every linked account's folder", () => {
|
||||
const info = JSON.stringify({
|
||||
personal: { path: "D:\\Dropbox", host: 1 },
|
||||
business: { path: "D:\\Dropbox (Acme)", host: 2 },
|
||||
});
|
||||
expect(dropboxRoots(info)).toEqual(["D:\\Dropbox", "D:\\Dropbox (Acme)"]);
|
||||
});
|
||||
|
||||
it("finds nothing in a file it cannot read", () => {
|
||||
expect(dropboxRoots("{ not json")).toEqual([]);
|
||||
expect(dropboxRoots("null")).toEqual([]);
|
||||
expect(dropboxRoots('{"personal":{}}')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("windowsCloudSyncKind", () => {
|
||||
// No LOCALAPPDATA: nothing is read from disk, only the fixed locations apply.
|
||||
const env = { OneDrive: "C:\\Users\\me\\OneDrive" };
|
||||
|
||||
it("names the service a folder sits under", async () => {
|
||||
expect(await windowsCloudSyncKind("C:\\Users\\me\\OneDrive\\Projects\\a", home, env)).toBe("OneDrive");
|
||||
expect(await windowsCloudSyncKind("C:\\Users\\me\\Dropbox\\a", home, env)).toBe("Dropbox");
|
||||
expect(await windowsCloudSyncKind("C:\\Users\\me\\iCloudDrive\\a", home, env)).toBe("iCloud Drive");
|
||||
});
|
||||
|
||||
it("leaves plain local disk alone", async () => {
|
||||
expect(await windowsCloudSyncKind("C:\\Users\\me\\Videos\\a", home, env)).toBeNull();
|
||||
expect(await windowsCloudSyncKind("G:\\My Drive\\a", home, env)).toBeNull();
|
||||
});
|
||||
});
|
||||
@ -1,89 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Where the sync services keep their folders on Windows. macOS marks a synced
|
||||
// folder with a File Provider attribute that can simply be asked for; Windows
|
||||
// has nothing like it, so each service is found the way it announces itself:
|
||||
// OneDrive through its environment variables, Dropbox through the info.json
|
||||
// it writes for exactly this purpose, Google Drive through the streaming
|
||||
// drive it mounts, iCloud through its fixed folder.
|
||||
|
||||
import { access, readFile } from "node:fs/promises";
|
||||
import { win32 } from "node:path";
|
||||
|
||||
/** A folder a service syncs, and the service's name as the warning spells it. */
|
||||
export type SyncRoot = [dir: string, label: string];
|
||||
|
||||
const exists = (path: string): Promise<boolean> => access(path).then(() => true, () => false);
|
||||
|
||||
/** Whether `path` is `root` or inside it, the way Windows compares paths: without case. */
|
||||
export function isUnder(path: string, root: string): boolean {
|
||||
const child = win32.resolve(path).toLowerCase();
|
||||
const parent = win32.resolve(root).toLowerCase().replace(/\\+$/, "");
|
||||
return child === parent || child.startsWith(parent + "\\");
|
||||
}
|
||||
|
||||
/** The folders named in Dropbox's info.json: one per linked account, personal and business. */
|
||||
export function dropboxRoots(infoJson: string): string[] {
|
||||
try {
|
||||
const info: unknown = JSON.parse(infoJson);
|
||||
if (typeof info !== "object" || info === null) return [];
|
||||
return Object.values(info)
|
||||
.map((account) => (account as { path?: unknown } | null)?.path)
|
||||
.filter((path): path is string => typeof path === "string" && path !== "");
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** Every sync root that can be named without looking at the path in question. */
|
||||
export async function windowsSyncRoots(home: string, env: NodeJS.ProcessEnv = process.env): Promise<SyncRoot[]> {
|
||||
const roots: SyncRoot[] = [[win32.join(home, "iCloudDrive"), "iCloud Drive"]];
|
||||
|
||||
for (const key of ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]) {
|
||||
const dir = env[key];
|
||||
if (dir) roots.push([dir, "OneDrive"]);
|
||||
}
|
||||
|
||||
const dropbox: string[] = [];
|
||||
for (const base of [env.LOCALAPPDATA, env.APPDATA]) {
|
||||
if (!base) continue;
|
||||
const text = await readFile(win32.join(base, "Dropbox", "info.json"), "utf8").catch(() => null);
|
||||
if (text) dropbox.push(...dropboxRoots(text));
|
||||
}
|
||||
// No info.json (an old or half-installed client): the default location.
|
||||
if (dropbox.length === 0) dropbox.push(win32.join(home, "Dropbox"));
|
||||
for (const dir of dropbox) roots.push([dir, "Dropbox"]);
|
||||
|
||||
// Google Drive in mirror mode keeps a real folder, by default in the home.
|
||||
if (await driveFsInstalled(env)) {
|
||||
roots.push([win32.join(home, "My Drive"), "Google Drive"], [win32.join(home, "Google Drive"), "Google Drive"]);
|
||||
}
|
||||
|
||||
return roots;
|
||||
}
|
||||
|
||||
function driveFsInstalled(env: NodeJS.ProcessEnv): Promise<boolean> {
|
||||
return env.LOCALAPPDATA ? exists(win32.join(env.LOCALAPPDATA, "Google", "DriveFS")) : Promise.resolve(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `path` is on Google Drive's streaming drive: a drive letter of its
|
||||
* own (G: unless the user moved it) whose root holds `My Drive`. The letter is
|
||||
* only in the client's database, so the drive is recognised by that shape,
|
||||
* and only on a machine that has the client.
|
||||
*/
|
||||
export async function onGoogleDriveStream(path: string, env: NodeJS.ProcessEnv = process.env): Promise<boolean> {
|
||||
const root = win32.parse(win32.resolve(path)).root;
|
||||
if (!/^[a-z]:\\$/i.test(root)) return false;
|
||||
return (await driveFsInstalled(env)) && (await exists(win32.join(root, "My Drive")));
|
||||
}
|
||||
|
||||
/** The service syncing `path` on Windows, or null. */
|
||||
export async function windowsCloudSyncKind(path: string, home: string, env: NodeJS.ProcessEnv = process.env): Promise<string | null> {
|
||||
for (const [dir, label] of await windowsSyncRoots(home, env)) {
|
||||
if (isUnder(path, dir)) return label;
|
||||
}
|
||||
return (await onGoogleDriveStream(path, env)) ? "Google Drive" : null;
|
||||
}
|
||||
@ -4,16 +4,6 @@
|
||||
|
||||
import type { LogEntry, ToolArgs, ToolResult } from "@diffusionstudio/dapi";
|
||||
|
||||
/** The main window, as the `window` tool drives it. */
|
||||
export type AppWindow = {
|
||||
/** Whether the window is out for the user. */
|
||||
visible(): boolean;
|
||||
/** Shows and focuses it, creating it when there is none. */
|
||||
show(): Promise<void>;
|
||||
/** Puts it away; the app keeps running in the background. */
|
||||
hide(): void;
|
||||
};
|
||||
|
||||
/** What a main-process handler gets besides its arguments. */
|
||||
export type MainContext = {
|
||||
/** Fires when the caller cancels or goes away. */
|
||||
@ -22,12 +12,10 @@ export type MainContext = {
|
||||
logs(): LogEntry[];
|
||||
/** The app's version. */
|
||||
version: string;
|
||||
/** The main window. */
|
||||
window: AppWindow;
|
||||
};
|
||||
|
||||
/** The tools that need the file system, a child process or the window itself, not a renderer. */
|
||||
export type MainToolName = "logs" | "report" | "window";
|
||||
/** The tools that need the file system or a child process, not a window. */
|
||||
export type MainToolName = "logs" | "fonts" | "report";
|
||||
|
||||
export type MainHandler<N extends MainToolName> = (args: ToolArgs<N>, ctx: MainContext) => Promise<ToolResult<N>>;
|
||||
|
||||
|
||||
89
apps/desktop/src/dapi/handlers/fonts.ts
Normal file
@ -0,0 +1,89 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { platform } from "node:os";
|
||||
import { DapiError, FONT_LIMIT } from "@diffusionstudio/dapi";
|
||||
|
||||
import type { FontFamily } from "@diffusionstudio/dapi";
|
||||
import type { MainHandler } from "../handler";
|
||||
|
||||
// JXA script that walks every registered font family via NSFontManager and
|
||||
// emits each variant's CSS-style weight, italic flag, and CSS `local()` source.
|
||||
// Runs via `osascript`.
|
||||
const LIST_FONTS_JXA = `
|
||||
ObjC.import("AppKit");
|
||||
|
||||
function nsfmWeightToCss(w) {
|
||||
if (w <= 1) return "100";
|
||||
if (w <= 2) return "200";
|
||||
if (w <= 3) return "300";
|
||||
if (w <= 5) return "400";
|
||||
if (w <= 6) return "500";
|
||||
if (w <= 8) return "600";
|
||||
if (w <= 9) return "700";
|
||||
if (w <= 11) return "800";
|
||||
return "900";
|
||||
}
|
||||
|
||||
function run() {
|
||||
var fm = $.NSFontManager.sharedFontManager;
|
||||
var families = fm.availableFontFamilies;
|
||||
var out = [];
|
||||
for (var i = 0; i < families.count; i++) {
|
||||
var family = ObjC.unwrap(families.objectAtIndex(i));
|
||||
if (family.charAt(0) === ".") continue;
|
||||
var members = fm.availableMembersOfFontFamily(family);
|
||||
if (!members || members.isNil()) continue;
|
||||
var variants = [];
|
||||
for (var j = 0; j < members.count; j++) {
|
||||
var m = members.objectAtIndex(j);
|
||||
var fontName = ObjC.unwrap(m.objectAtIndex(0));
|
||||
var styleName = ObjC.unwrap(m.objectAtIndex(1));
|
||||
var weight = ObjC.unwrap(m.objectAtIndex(2));
|
||||
var traits = ObjC.unwrap(m.objectAtIndex(3));
|
||||
var fullName = styleName === "Regular" ? family : family + " " + styleName;
|
||||
variants.push({
|
||||
weight: nsfmWeightToCss(weight),
|
||||
style: (traits & 1) !== 0 ? "italic" : "normal",
|
||||
source: "local('" + fullName + "'), local('" + fontName + "')",
|
||||
});
|
||||
}
|
||||
if (variants.length > 0) out.push({ family: family, variants: variants });
|
||||
}
|
||||
return JSON.stringify(out);
|
||||
}
|
||||
`;
|
||||
|
||||
function listLocalFonts(): FontFamily[] {
|
||||
if (platform() !== "darwin") {
|
||||
throw new DapiError("unsupported", "fonts is only supported on macOS.");
|
||||
}
|
||||
const result = spawnSync("osascript", ["-l", "JavaScript", "-e", LIST_FONTS_JXA], {
|
||||
encoding: "utf8",
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
});
|
||||
if (result.status !== 0) {
|
||||
throw new Error(result.stderr.trim() || "Failed to enumerate fonts.");
|
||||
}
|
||||
return JSON.parse(result.stdout.trim()) as FontFamily[];
|
||||
}
|
||||
|
||||
export const fonts: MainHandler<"fonts"> = async ({ family, weights, style, limit = FONT_LIMIT }) => {
|
||||
const pattern = family?.toLowerCase();
|
||||
const wanted = weights && weights.length > 0 ? new Set(weights) : null;
|
||||
|
||||
const families: FontFamily[] = [];
|
||||
for (const entry of listLocalFonts()) {
|
||||
if (pattern && !entry.family.toLowerCase().includes(pattern)) continue;
|
||||
const variants = entry.variants.filter((v) => {
|
||||
if (wanted && !wanted.has(v.weight)) return false;
|
||||
if (style && v.style !== style) return false;
|
||||
return true;
|
||||
});
|
||||
if (variants.length === 0) continue;
|
||||
families.push({ family: entry.family, variants });
|
||||
}
|
||||
return { families: families.slice(0, limit), total: families.length };
|
||||
};
|
||||
@ -3,10 +3,10 @@
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { logs } from "./logs";
|
||||
import { fonts } from "./fonts";
|
||||
import { report } from "./report";
|
||||
import { window } from "./window";
|
||||
|
||||
import type { MainHandlers } from "../handler";
|
||||
|
||||
/** Every tool main answers itself, keyed by its catalog name. */
|
||||
export const mainHandlers: MainHandlers = { logs, report, window };
|
||||
export const mainHandlers: MainHandlers = { logs, fonts, report };
|
||||
|
||||
@ -11,8 +11,7 @@ import type { MainContext } from "../handler";
|
||||
|
||||
const entry = (ts: number, message: string, level: LogEntry["level"] = "info"): LogEntry => ({ ts, level, message, source: "" });
|
||||
|
||||
const noWindow = { visible: () => false, show: async () => {}, hide: () => {} };
|
||||
const ctx = (entries: LogEntry[]): MainContext => ({ signal: new AbortController().signal, logs: () => entries, version: "0", window: noWindow });
|
||||
const ctx = (entries: LogEntry[]): MainContext => ({ signal: new AbortController().signal, logs: () => entries, version: "0" });
|
||||
|
||||
describe("logs", () => {
|
||||
it("returns the last LOG_TAIL entries when no tail is given", async () => {
|
||||
|
||||
@ -1,15 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import type { MainHandler } from "../handler";
|
||||
|
||||
export const window: MainHandler<"window"> = async ({ visible }, ctx) => {
|
||||
if (visible === true) {
|
||||
await ctx.window.show();
|
||||
} else if (visible === false) {
|
||||
ctx.window.hide();
|
||||
}
|
||||
|
||||
return { visible: ctx.window.visible() };
|
||||
};
|
||||
@ -14,6 +14,7 @@ import { DapiHttpServer } from "./http";
|
||||
const PORT = 3200 + Math.floor(Math.random() * 500);
|
||||
const PATH = "/mcp";
|
||||
let server: DapiHttpServer;
|
||||
let firstConnections = 0;
|
||||
let sessionsCreated = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
@ -21,6 +22,7 @@ beforeAll(async () => {
|
||||
host: "127.0.0.1",
|
||||
port: PORT,
|
||||
path: PATH,
|
||||
onFirstConnection: () => void firstConnections++,
|
||||
createSession() {
|
||||
sessionsCreated++;
|
||||
const session = new McpServer({ name: "test", version: "0.0.0" }, { instructions: "Test instructions." });
|
||||
@ -58,11 +60,12 @@ describe("mcp over http", () => {
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it("gives each client its own session", async () => {
|
||||
it("gives each client its own session and reports the first once", async () => {
|
||||
const before = sessionsCreated;
|
||||
const a = await connect();
|
||||
const b = await connect();
|
||||
expect(sessionsCreated - before).toBe(2);
|
||||
expect(firstConnections).toBe(1);
|
||||
await a.close();
|
||||
await b.close();
|
||||
});
|
||||
|
||||
@ -23,8 +23,16 @@ export type HttpServerDeps = {
|
||||
path: string;
|
||||
/** A fresh MCP server with the tools and resources registered, one per session. */
|
||||
createSession(): McpServer;
|
||||
/**
|
||||
* Called once, when the first session initializes — unless that session
|
||||
* says `?client=chat` in its URL: the in-app chat is watched by the user,
|
||||
* so it must not switch the app into remote-controlled mode.
|
||||
*/
|
||||
onFirstConnection(): void;
|
||||
};
|
||||
|
||||
const CHAT_CLIENT = "chat";
|
||||
|
||||
type Session = { transport: StreamableHTTPServerTransport; server: McpServer };
|
||||
|
||||
const SESSION_HEADER = "mcp-session-id";
|
||||
@ -33,6 +41,7 @@ export class DapiHttpServer {
|
||||
private readonly deps: HttpServerDeps;
|
||||
private readonly sessions = new Map<string, Session>();
|
||||
private server: Server | null = null;
|
||||
private connected = false;
|
||||
|
||||
constructor(deps: HttpServerDeps) {
|
||||
this.deps = deps;
|
||||
@ -89,14 +98,14 @@ export class DapiHttpServer {
|
||||
}
|
||||
// No session: either an `initialize`, which the transport answers with
|
||||
// a new id, or a stray request it rejects with 400.
|
||||
await this.open().transport.handleRequest(req, res);
|
||||
await this.open(url.searchParams.get("client")).transport.handleRequest(req, res);
|
||||
} catch (error) {
|
||||
console.error("[dapi] http request failed:", error);
|
||||
if (!res.headersSent) res.writeHead(500, { "content-type": "text/plain" }).end("Internal error");
|
||||
}
|
||||
}
|
||||
|
||||
private open(): Session {
|
||||
private open(client: string | null): Session {
|
||||
const server = this.deps.createSession();
|
||||
const hosts = [this.deps.host, "localhost"];
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
@ -105,6 +114,10 @@ export class DapiHttpServer {
|
||||
allowedHosts: [...hosts, ...hosts.map((host) => `${host}:${this.deps.port}`)],
|
||||
onsessioninitialized: (id) => {
|
||||
this.sessions.set(id, session);
|
||||
if (!this.connected && client !== CHAT_CLIENT) {
|
||||
this.connected = true;
|
||||
this.deps.onFirstConnection();
|
||||
}
|
||||
},
|
||||
onsessionclosed: (id) => {
|
||||
this.sessions.delete(id);
|
||||
|
||||
@ -2,10 +2,10 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { afterAll, describe, expect, it, vi } from "vitest";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { present, toCallToolResult } from "./present";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "dapi-present-"));
|
||||
@ -25,7 +25,7 @@ describe("present", () => {
|
||||
});
|
||||
|
||||
it("picks a fresh temp directory when none is given", async () => {
|
||||
const presented = await present("grab", { path: "/c.mp4" }, [{ timecode: "0f", png: png(3) }]);
|
||||
const presented = await present("media_grab", { path: "/c.mp4" }, [{ timecode: "0f", png: png(3) }]);
|
||||
const { path } = (presented.output as { images: Array<{ path: string }> }).images[0]!;
|
||||
expect(path).toMatch(/dapi-grab-.*[\\/]0f\.png$/);
|
||||
rmSync(join(path, ".."), { recursive: true, force: true });
|
||||
@ -33,20 +33,20 @@ describe("present", () => {
|
||||
|
||||
it("keeps a preview's other fields next to the path", async () => {
|
||||
const file = join(dir, "wave.png");
|
||||
const presented = await present("waveform", { path: "/c.mp4", output: file }, { png: png(4), silences: [{ start: 0, end: 1 }] });
|
||||
const presented = await present("media_waveform", { path: "/c.mp4", output: file }, { png: png(4), silences: [{ start: 0, end: 1 }] });
|
||||
expect(presented.output).toEqual({ path: file, silences: [{ start: 0, end: 1 }] });
|
||||
});
|
||||
|
||||
it("writes a preview or transcript into an output that names an existing directory", async () => {
|
||||
const out = join(dir, "into");
|
||||
mkdirSync(out, { recursive: true });
|
||||
const preview = await present("waveform", { path: "/c.mp4", output: out }, { png: png(7), silences: [] });
|
||||
const preview = await present("media_waveform", { path: "/c.mp4", output: out }, { png: png(7), silences: [] });
|
||||
const previewPath = (preview.output as { path: string }).path;
|
||||
expect(dirname(previewPath)).toBe(out);
|
||||
expect(basename(previewPath)).toMatch(/^dapi-waveform-.*\.png$/);
|
||||
expect(readFileSync(previewPath)).toEqual(Buffer.from(png(7)));
|
||||
|
||||
const transcript = await present("transcribe", { path: "/c.mp4", output: out }, { segments: [] });
|
||||
const transcript = await present("media_transcribe", { path: "/c.mp4", output: out }, { segments: [] });
|
||||
const transcriptPath = (transcript.output as { path: string }).path;
|
||||
expect(transcriptPath).toMatch(/dapi-transcript-.*\.json$/);
|
||||
expect(JSON.parse(readFileSync(transcriptPath, "utf8"))).toEqual({ segments: [] });
|
||||
@ -64,7 +64,7 @@ describe("present", () => {
|
||||
it("writes a transcript to a file, unchanged, and returns its path and size", async () => {
|
||||
const file = join(dir, "talk.json");
|
||||
const segments = [{ text: "Hi there", words: [{ text: "Hi", start: 0, end: 0.2 }, { text: "there", start: 0.3, end: 0.6 }] }];
|
||||
const presented = await present("transcribe", { path: "/c.mp4", output: file }, { segments });
|
||||
const presented = await present("media_transcribe", { path: "/c.mp4", output: file }, { segments });
|
||||
expect(presented).toEqual({ output: { path: file, segments: 1, words: 2 }, images: [] });
|
||||
expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ segments });
|
||||
});
|
||||
@ -89,92 +89,3 @@ describe("toCallToolResult", () => {
|
||||
expect(toCallToolResult({ output: {}, images: large }).content).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("present a generation job", () => {
|
||||
const job = (id: string, status: string, assets: Array<Record<string, unknown>>) => ({
|
||||
job: { id, status, credits: 4, etaSeconds: 10, etaRemainingSeconds: null, error: null, assets },
|
||||
saveTo: null as string | null,
|
||||
});
|
||||
const file = (filename: string) => ({ url: `https://files.test/${filename}`, filename, mimeType: "image/png", size: 8 });
|
||||
|
||||
it("passes a job still running through as the API has it", async () => {
|
||||
const running = job("j-running", "running", []);
|
||||
expect((await present("job", { id: "j-running" }, running)).output).toEqual(running.job);
|
||||
});
|
||||
|
||||
it("downloads a succeeded job's files once, to the output numbered and with the made extension", async () => {
|
||||
const fetch = vi.fn(async (url: string) => new Response(new Uint8Array([url.length])));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
try {
|
||||
const out = join(dir, "generated", "fox.jpg");
|
||||
const done = { ...job("j-done", "succeeded", [file("red-fox.png"), file("red-fox-2.png")]), saveTo: out };
|
||||
const first = await present("job", { id: "j-done" }, done);
|
||||
const again = await present("job", { id: "j-done" }, done);
|
||||
const assets = (first.output as { assets: Array<Record<string, unknown>> }).assets;
|
||||
expect(assets.map((asset) => asset.path)).toEqual([join(dir, "generated", "fox-1.png"), join(dir, "generated", "fox-2.png")]);
|
||||
expect(assets[0]).not.toHaveProperty("url");
|
||||
expect(assets[0]).toMatchObject({ filename: "red-fox.png", mimeType: "image/png" });
|
||||
expect(again.output).toEqual(first.output);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("writes a single file at the output, over a file already there", async () => {
|
||||
vi.stubGlobal("fetch", async () => new Response("new"));
|
||||
try {
|
||||
const out = join(dir, "single.png");
|
||||
writeFileSync(out, "old");
|
||||
const presented = await present("job", { id: "j-one" }, { ...job("j-one", "succeeded", [file("x.png")]), saveTo: out });
|
||||
expect((presented.output as { assets: Array<{ path: string }> }).assets[0]!.path).toBe(out);
|
||||
expect(readFileSync(out, "utf8")).toBe("new");
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("saves into a directory of the job's own under the temp dir when no directory is given", async () => {
|
||||
vi.stubGlobal("fetch", async () => new Response(new Uint8Array([1])));
|
||||
try {
|
||||
const presented = await present("generate", { model: "flux-2-klein" }, job("j-temp", "succeeded", [file("a.png")]));
|
||||
const path = (presented.output as { assets: Array<{ path: string }> }).assets[0]!.path;
|
||||
expect(path).toMatch(/dapi-generate-j-temp[\\/]a\.png$/);
|
||||
rmSync(dirname(path), { recursive: true, force: true });
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves files the renderer saved into the library as they are", async () => {
|
||||
const saved = job("j-lib", "succeeded", [{ filename: "a.png", path: "/p/assets/a.png", src: "a.png" }]);
|
||||
expect((await present("job", { id: "j-lib" }, saved)).output).toEqual(saved.job);
|
||||
});
|
||||
it("writes a local job's files from their bytes, to the output, once", async () => {
|
||||
const out = join(dir, "masks", "skater.mask");
|
||||
const done = { ...job("local-mask", "succeeded", [{ filename: "Tracking 1.mask", mimeType: "", size: 4, bytes: png(9, 4) }]), saveTo: out };
|
||||
const first = await present("job", { id: "local-mask" }, done);
|
||||
writeFileSync(out, "edited since");
|
||||
const again = await present("job", { id: "local-mask" }, done);
|
||||
const assets = (first.output as { assets: Array<Record<string, unknown>> }).assets;
|
||||
expect(assets).toEqual([{ filename: "Tracking 1.mask", mimeType: "", size: 4, path: out }]);
|
||||
expect(again.output).toEqual(first.output);
|
||||
expect(readFileSync(out, "utf8")).toBe("edited since");
|
||||
});
|
||||
|
||||
it("writes a local job's picture to the temp dir, inline only the first time, and names it in its details", async () => {
|
||||
const details = { frameRate: 30, start: 1, end: 1.033, frames: 1, bbox: null, lost: [] };
|
||||
const preview = { ...job("local-preview", "succeeded", []), image: png(8) };
|
||||
preview.job = { ...preview.job, details } as typeof preview.job;
|
||||
const first = await present("generate", { model: "sam-2.1" }, preview);
|
||||
const image = (first.output as { details: { image: string } }).details.image;
|
||||
expect(image).toMatch(/dapi-local-preview\.png$/);
|
||||
expect(first.output).toEqual({ ...preview.job, details: { ...details, image } });
|
||||
expect(first.images).toEqual([{ path: image, png: png(8) }]);
|
||||
expect(readFileSync(image)).toEqual(Buffer.from(png(8)));
|
||||
|
||||
const again = await present("job", { id: "local-preview" }, preview);
|
||||
expect(again).toEqual({ output: first.output, images: [] });
|
||||
rmSync(image, { force: true });
|
||||
});
|
||||
});
|
||||
|
||||
@ -2,16 +2,14 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { existsSync, realpathSync } from "node:fs";
|
||||
import { existsSync } from "node:fs";
|
||||
import { mkdir, mkdtemp, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { dirname, join } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { generatedPath } from "@diffusionstudio/dapi";
|
||||
|
||||
import type { GenerationResult, TimecodedImage, ToolArgs, ToolName, ToolOutput, ToolResult } from "@diffusionstudio/dapi";
|
||||
import type { TimecodedImage, ToolArgs, ToolName, ToolOutput, ToolResult } from "@diffusionstudio/dapi";
|
||||
|
||||
/** A file the tool wrote, kept in memory only long enough to decide whether to inline it. */
|
||||
export type WrittenImage = { path: string; png: Uint8Array };
|
||||
@ -24,37 +22,20 @@ const INLINE_MAX_BYTES = 1 << 20;
|
||||
|
||||
const APP_SLUG = "diffusion-studio";
|
||||
|
||||
/**
|
||||
* The temp dir with its real spelling. On Windows `%TEMP%` is often set with short names
|
||||
*/
|
||||
function tempDir(): string {
|
||||
const dir = tmpdir();
|
||||
try {
|
||||
return realpathSync.native(dir);
|
||||
} catch {
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
|
||||
export async function present(name: ToolName, args: unknown, result: unknown): Promise<Presented> {
|
||||
switch (name) {
|
||||
case "capture":
|
||||
return presentImages(result as ToolResult<"capture">, (args as ToolArgs<"capture">).output, "capture");
|
||||
case "grab":
|
||||
return presentImages(result as ToolResult<"grab">, (args as ToolArgs<"grab">).output, "grab");
|
||||
case "filmstrip":
|
||||
return presentPreview(result as ToolResult<"filmstrip">, (args as ToolArgs<"filmstrip">).output, "filmstrip");
|
||||
case "waveform":
|
||||
return presentPreview(result as ToolResult<"waveform">, (args as ToolArgs<"waveform">).output, "waveform");
|
||||
case "media_grab":
|
||||
return presentImages(result as ToolResult<"media_grab">, (args as ToolArgs<"media_grab">).output, "grab");
|
||||
case "media_filmstrip":
|
||||
return presentPreview(result as ToolResult<"media_filmstrip">, (args as ToolArgs<"media_filmstrip">).output, "filmstrip");
|
||||
case "media_waveform":
|
||||
return presentPreview(result as ToolResult<"media_waveform">, (args as ToolArgs<"media_waveform">).output, "waveform");
|
||||
case "screenshot":
|
||||
return presentScreenshot(result as ToolResult<"screenshot">, (args as ToolArgs<"screenshot">).output);
|
||||
case "transcribe":
|
||||
return presentTranscript(result as ToolResult<"transcribe">, (args as ToolArgs<"transcribe">).output);
|
||||
case "generate":
|
||||
if ((args as ToolArgs<"generate">).estimate) return { output: result, images: [] };
|
||||
return presentJob(result as GenerationResult);
|
||||
case "job":
|
||||
return presentJob(result as GenerationResult);
|
||||
case "media_transcribe":
|
||||
return presentTranscript(result as ToolResult<"media_transcribe">, (args as ToolArgs<"media_transcribe">).output);
|
||||
default:
|
||||
return { output: result, images: [] };
|
||||
}
|
||||
@ -64,7 +45,7 @@ export async function present(name: ToolName, args: unknown, result: unknown): P
|
||||
// with its timecode (`08s10f`, or `0f-08s10f` for a sheet), which is the
|
||||
// filename too.
|
||||
async function presentImages(images: TimecodedImage[], output: string | undefined, kind: string): Promise<Presented> {
|
||||
const dir = output ?? (await mkdtemp(join(tempDir(), `dapi-${kind}-`)));
|
||||
const dir = output ?? (await mkdtemp(join(tmpdir(), `dapi-${kind}-`)));
|
||||
await mkdir(dir, { recursive: true });
|
||||
const written: WrittenImage[] = [];
|
||||
const refs: ToolOutput<"capture">["images"] = [];
|
||||
@ -83,7 +64,7 @@ async function presentImages(images: TimecodedImage[], output: string | undefine
|
||||
* the fresh name inside it rather than an EISDIR from writeFile.
|
||||
*/
|
||||
async function singleFilePath(output: string | undefined, name: string): Promise<string> {
|
||||
if (output === undefined) return join(tempDir(), name);
|
||||
if (output === undefined) return join(tmpdir(), name);
|
||||
const existing = await stat(output).catch(() => null);
|
||||
if (existing?.isDirectory()) return join(output, name);
|
||||
await mkdir(dirname(output), { recursive: true });
|
||||
@ -102,7 +83,7 @@ async function presentPreview(
|
||||
}
|
||||
|
||||
async function presentScreenshot(result: ToolResult<"screenshot">, output: string | undefined): Promise<Presented> {
|
||||
const dir = output ?? tempDir();
|
||||
const dir = output ?? tmpdir();
|
||||
await mkdir(dir, { recursive: true });
|
||||
const taken = new Date();
|
||||
let attempt = 1;
|
||||
@ -113,75 +94,14 @@ async function presentScreenshot(result: ToolResult<"screenshot">, output: strin
|
||||
return { output: presented, images: [{ path, png: result.png }] };
|
||||
}
|
||||
|
||||
async function presentTranscript(transcript: ToolResult<"transcribe">, output: string | undefined): Promise<Presented> {
|
||||
async function presentTranscript(transcript: ToolResult<"media_transcribe">, output: string | undefined): Promise<Presented> {
|
||||
const path = await singleFilePath(output, `dapi-transcript-${randomUUID()}.json`);
|
||||
await writeFile(path, JSON.stringify(transcript, null, 2));
|
||||
const words = transcript.segments.reduce((sum, segment) => sum + segment.words.length, 0);
|
||||
const presented: ToolOutput<"transcribe"> = { path, segments: transcript.segments.length, words };
|
||||
const presented: ToolOutput<"media_transcribe"> = { path, segments: transcript.segments.length, words };
|
||||
return { output: presented, images: [] };
|
||||
}
|
||||
|
||||
/** Files of succeeded jobs saved to disk, by job id: the first poll that sees a job succeed saves them, the rest reuse the paths. */
|
||||
const jobFiles = new Map<string, Promise<string[]>>();
|
||||
|
||||
/** Pictures of local jobs, by job id: each is written to the temp dir, and shown inline, the first poll it comes with. */
|
||||
const jobImages = new Map<string, string>();
|
||||
|
||||
/**
|
||||
* A job's files bound for disk are saved once it has succeeded — downloaded
|
||||
* from their `url`, or written from the `bytes` a local model made — to
|
||||
* `saveTo` (see `generatedPath`; a file already there is written over, as the
|
||||
* other tools' outputs are) or under their own names into a directory of the
|
||||
* job's own under the temp dir, and their `url` or `bytes` is swapped for the
|
||||
* `path`. Files the renderer saved into the library arrive with their paths.
|
||||
* A local job's picture goes to the temp dir, named in `details.image`.
|
||||
*/
|
||||
async function presentJob({ job, saveTo, image }: GenerationResult): Promise<Presented> {
|
||||
const images: WrittenImage[] = [];
|
||||
let shown = job;
|
||||
if (image) {
|
||||
let path = jobImages.get(job.id);
|
||||
if (path === undefined) {
|
||||
path = join(tempDir(), `dapi-${job.id}.png`);
|
||||
await writeFile(path, image);
|
||||
jobImages.set(job.id, path);
|
||||
images.push({ path, png: image });
|
||||
}
|
||||
shown = { ...job, details: { ...job.details, image: path } };
|
||||
}
|
||||
|
||||
const pending = job.assets.filter((file) => file.url !== undefined || file.bytes !== undefined);
|
||||
if (job.status !== "succeeded" || pending.length === 0) return { output: shown, images };
|
||||
|
||||
let paths = jobFiles.get(job.id);
|
||||
if (!paths) {
|
||||
const temp = join(tempDir(), `dapi-generate-${job.id}`);
|
||||
const targets = job.assets.map((file, i) =>
|
||||
saveTo === null ? join(temp, basename(file.filename)) : generatedPath(saveTo, file.filename, i, job.assets.length),
|
||||
);
|
||||
paths = saveAll(job.assets, targets);
|
||||
paths.catch(() => jobFiles.delete(job.id));
|
||||
jobFiles.set(job.id, paths);
|
||||
}
|
||||
const written = await paths;
|
||||
const assets = job.assets.map(({ url: _url, bytes: _bytes, ...file }, i) => ({ ...file, path: written[i] }));
|
||||
return { output: { ...shown, assets }, images };
|
||||
}
|
||||
|
||||
async function saveAll(files: GenerationResult["job"]["assets"], targets: string[]): Promise<string[]> {
|
||||
for (const [i, file] of files.entries()) {
|
||||
await mkdir(dirname(targets[i]!), { recursive: true });
|
||||
await writeFile(targets[i]!, file.bytes ?? (await download(file.url!, file.filename)));
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
async function download(url: string, filename: string): Promise<Uint8Array> {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) throw new Error(`Could not download ${filename} (${response.status})`);
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
function screenshotFilename(taken: Date, attempt: number): string {
|
||||
const pad = (value: number) => String(value).padStart(2, "0");
|
||||
const date = [taken.getFullYear(), pad(taken.getMonth() + 1), pad(taken.getDate())].join("-");
|
||||
|
||||
@ -3,10 +3,9 @@
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { ipcMain } from "electron";
|
||||
import { app, BrowserWindow, ipcMain } from "electron";
|
||||
import { DAPI_WIRE, DapiError } from "@diffusionstudio/dapi";
|
||||
|
||||
import type { BrowserWindow } from "electron";
|
||||
import type { DapiCall, DapiCancel, DapiReply } from "@diffusionstudio/dapi";
|
||||
|
||||
type InFlight = {
|
||||
@ -14,33 +13,15 @@ type InFlight = {
|
||||
reject(error: Error): void;
|
||||
};
|
||||
|
||||
/** Where renderer calls find their window. */
|
||||
export type RendererHost = {
|
||||
/** The main window, created hidden when there is none; `fresh` when this call created it. */
|
||||
acquire(): { window: BrowserWindow; fresh: boolean };
|
||||
/** The project the editor last had open, to reopen in a window created for a call. */
|
||||
lastProject(): string | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Runs renderer tools from main: one `dapi:call` per request, answered by
|
||||
* `dapi:reply`, or `dapi:cancel` if the caller gives up. There may be no
|
||||
* window when a call arrives — it is only kept while something needs it — so
|
||||
* a call creates one, and waits for it to load and to reopen the project the
|
||||
* agent was working on. A window that reloads or dies fails the calls it was
|
||||
* answering.
|
||||
* `dapi:reply`, or `dapi:cancel` if the caller gives up. Calls wait for the
|
||||
* current window to finish loading; a window that reloads or dies fails the
|
||||
* calls it was answering.
|
||||
*/
|
||||
export class RendererCalls {
|
||||
private readonly host: RendererHost;
|
||||
private readonly inFlight = new Map<string, InFlight>();
|
||||
private readonly tracked = new WeakSet<BrowserWindow>();
|
||||
// Settles once the current window has loaded, and reopened the project
|
||||
// when it was created for a call. Every call waits on it.
|
||||
private ready: Promise<BrowserWindow> | null = null;
|
||||
|
||||
constructor(host: RendererHost) {
|
||||
this.host = host;
|
||||
}
|
||||
private window: BrowserWindow | null = null;
|
||||
|
||||
start(): void {
|
||||
ipcMain.on(DAPI_WIRE.REPLY, (_event, reply: DapiReply) => {
|
||||
@ -50,47 +31,14 @@ export class RendererCalls {
|
||||
if (reply.ok) call.resolve(reply.data);
|
||||
else call.reject(reply.error.code ? new DapiError(reply.error.code, reply.error.message) : new Error(reply.error.message));
|
||||
});
|
||||
|
||||
app.on("browser-window-created", (_event, window) => this.track(window));
|
||||
const windows = BrowserWindow.getAllWindows();
|
||||
if (windows.length > 0) this.track(windows[windows.length - 1]!);
|
||||
}
|
||||
|
||||
async call(tool: string, args: unknown, signal: AbortSignal): Promise<unknown> {
|
||||
const window = await this.window(tool);
|
||||
if (window.isDestroyed()) {
|
||||
throw new Error("The app window closed before replying");
|
||||
}
|
||||
return this.send(window, tool, args, signal);
|
||||
}
|
||||
|
||||
// The window to answer on. One created here is tracked, and gets the last
|
||||
// project reopened — unless the call is itself an `open` — since the calls
|
||||
// that follow assume the project the agent opened is still open. A project
|
||||
// that no longer opens is left to the call to report.
|
||||
private window(tool: string): Promise<BrowserWindow> {
|
||||
const { window, fresh } = this.host.acquire();
|
||||
// Loaded before, but it may have reloaded since.
|
||||
if (!fresh && this.ready) {
|
||||
return this.ready.then(loaded);
|
||||
}
|
||||
|
||||
this.track(window);
|
||||
const dir = fresh && tool !== "open" ? this.host.lastProject() : null;
|
||||
const ready = loaded(window).then(async (loadedWindow) => {
|
||||
if (dir) {
|
||||
await this.send(loadedWindow, "open", { dir }, new AbortController().signal).catch((error: Error) =>
|
||||
console.warn(`[dapi] could not reopen ${dir}: ${error.message}`),
|
||||
);
|
||||
}
|
||||
return loadedWindow;
|
||||
});
|
||||
this.ready = ready;
|
||||
// A window that failed to load is not waited on again: the next call
|
||||
// finds out afresh.
|
||||
ready.catch(() => {
|
||||
if (this.ready === ready) this.ready = null;
|
||||
});
|
||||
return ready;
|
||||
}
|
||||
|
||||
private send(window: BrowserWindow, tool: string, args: unknown, signal: AbortSignal): Promise<unknown> {
|
||||
const window = await this.ready();
|
||||
const id = randomUUID();
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
@ -114,13 +62,12 @@ export class RendererCalls {
|
||||
}
|
||||
|
||||
private track(window: BrowserWindow): void {
|
||||
if (this.tracked.has(window)) return;
|
||||
this.tracked.add(window);
|
||||
this.window = window;
|
||||
const fail = (why: string) => () => this.failAll(why);
|
||||
window.webContents.on("did-start-loading", fail("The app reloaded before replying"));
|
||||
window.webContents.on("render-process-gone", fail("The app's renderer crashed"));
|
||||
window.on("closed", () => {
|
||||
this.ready = null;
|
||||
if (this.window === window) this.window = null;
|
||||
this.failAll("The app window closed before replying");
|
||||
});
|
||||
}
|
||||
@ -131,33 +78,33 @@ export class RendererCalls {
|
||||
for (const call of calls) call.reject(new Error(message));
|
||||
}
|
||||
|
||||
}
|
||||
// Resolves with the current window once it has finished loading.
|
||||
private ready(timeoutMs = 30000): Promise<BrowserWindow> {
|
||||
const window = this.window;
|
||||
if (!window || window.isDestroyed()) return Promise.reject(new Error("The app has no window"));
|
||||
if (window.webContents.isCrashed()) return Promise.reject(new Error("The app's renderer crashed"));
|
||||
if (!window.webContents.isLoading()) return Promise.resolve(window);
|
||||
|
||||
// Resolves with the window once it has finished loading.
|
||||
function loaded(window: BrowserWindow, timeoutMs = 30000): Promise<BrowserWindow> {
|
||||
if (window.isDestroyed()) return Promise.reject(new Error("The app has no window"));
|
||||
if (window.webContents.isCrashed()) return Promise.reject(new Error("The app's renderer crashed"));
|
||||
if (!window.webContents.isLoading()) return Promise.resolve(window);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error("The app did not become ready in time"));
|
||||
}, timeoutMs);
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
window.webContents.off("did-finish-load", onLoad);
|
||||
window.webContents.off("did-fail-load", onFail);
|
||||
};
|
||||
const onLoad = () => {
|
||||
cleanup();
|
||||
resolve(window);
|
||||
};
|
||||
const onFail = () => {
|
||||
cleanup();
|
||||
reject(new Error("The app failed to load"));
|
||||
};
|
||||
window.webContents.on("did-finish-load", onLoad);
|
||||
window.webContents.on("did-fail-load", onFail);
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
cleanup();
|
||||
reject(new Error("The app did not become ready in time"));
|
||||
}, timeoutMs);
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
window.webContents.off("did-finish-load", onLoad);
|
||||
window.webContents.off("did-fail-load", onFail);
|
||||
};
|
||||
const onLoad = () => {
|
||||
cleanup();
|
||||
resolve(window);
|
||||
};
|
||||
const onFail = () => {
|
||||
cleanup();
|
||||
reject(new Error("The app failed to load"));
|
||||
};
|
||||
window.webContents.on("did-finish-load", onLoad);
|
||||
window.webContents.on("did-fail-load", onFail);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@ -3,23 +3,20 @@
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { MCP_HOST, MCP_PATH, MCP_PORT, isDapiError, tools } from "@diffusionstudio/dapi";
|
||||
import { MCP_HOST, MCP_PATH, MCP_PORT, tools } from "@diffusionstudio/dapi";
|
||||
import { mainHandlers } from "./handlers";
|
||||
import { DapiHttpServer } from "./http";
|
||||
import { instructions } from "./docs";
|
||||
import { RendererCalls } from "./renderer-calls";
|
||||
import { serveCatalog } from "./tools-session";
|
||||
|
||||
import type { TrackProps } from "@diffusionstudio/api-contract";
|
||||
import type { LogEntry } from "@diffusionstudio/dapi";
|
||||
import type { AppWindow, MainContext, MainToolName } from "./handler";
|
||||
import type { RendererHost } from "./renderer-calls";
|
||||
import type { MainContext, MainToolName } from "./handler";
|
||||
|
||||
/**
|
||||
* The name the server introduces itself with, and so the namespace an agent
|
||||
* shows the tools under: `mcp__diffusion__<tool>`. The same word as our URL
|
||||
* scheme and the CLI's primary name (`dapi` still works there too, as an
|
||||
* alias).
|
||||
* scheme, and not `dapi`, which is the CLI.
|
||||
*/
|
||||
const SERVER_NAME = "diffusion";
|
||||
|
||||
@ -27,34 +24,28 @@ export type DapiServerDeps = {
|
||||
version: string;
|
||||
/** The app's console buffer, for `logs` and `report`. */
|
||||
logs(): LogEntry[];
|
||||
/** The main window: where renderer tools run, and what `window` shows and hides. */
|
||||
window: AppWindow & RendererHost & {
|
||||
/** Keeps the window from idling out while a call runs; returns the release. */
|
||||
hold(): () => void;
|
||||
};
|
||||
/** Called once, on the first connection: an agent is driving, so the UI may step back. */
|
||||
onFirstConnection(): void;
|
||||
/** The staged docs: INSTRUCTIONS.md, their path, and the skill headers, all for every session. Null when not staged. */
|
||||
docsDir: string | null;
|
||||
/** Told about every finished call, as `tool_called` analytics props. */
|
||||
onToolCall?(props: TrackProps): void;
|
||||
};
|
||||
|
||||
/**
|
||||
* The app's MCP server: Streamable HTTP on a fixed loopback port, the URL
|
||||
* agents register and the `diffusion` CLI calls. Each client gets its own MCP
|
||||
* agents register and the `dapi` CLI calls. Each client gets its own MCP
|
||||
* session over one catalog. Main-process tools run here; renderer tools are
|
||||
* forwarded over IPC and their results presented (files written, small
|
||||
* images inlined) before they go back out.
|
||||
*/
|
||||
export class DapiServer {
|
||||
private readonly deps: DapiServerDeps;
|
||||
private readonly renderer: RendererCalls;
|
||||
private readonly renderer = new RendererCalls();
|
||||
private readonly http: DapiHttpServer;
|
||||
private instructionsText: string | null = null;
|
||||
private httpReady: Promise<boolean> = Promise.resolve(false);
|
||||
|
||||
constructor(deps: DapiServerDeps) {
|
||||
this.deps = deps;
|
||||
this.renderer = new RendererCalls(deps.window);
|
||||
for (const tool of tools) {
|
||||
if (tool.environment === "main" && !(tool.name in mainHandlers)) {
|
||||
throw new Error(`Main-process tool "${tool.name}" has no handler`);
|
||||
@ -65,6 +56,7 @@ export class DapiServer {
|
||||
port: MCP_PORT,
|
||||
path: MCP_PATH,
|
||||
createSession: () => this.createSession(),
|
||||
onFirstConnection: () => deps.onFirstConnection(),
|
||||
});
|
||||
}
|
||||
|
||||
@ -101,36 +93,16 @@ export class DapiServer {
|
||||
// `name` is the machine identity, and matches the key we write into agent
|
||||
// configs; `title` is what a client shows a person.
|
||||
const session = new McpServer({ name: SERVER_NAME, title: "Diffusion Studio", version: this.deps.version }, { instructions: this.instructionsText });
|
||||
serveCatalog(session, async (tool, args, signal) => {
|
||||
const release = this.deps.window.hold();
|
||||
const startedAt = performance.now();
|
||||
// The failure's code (`not-found`, `busy`, …), never its message: messages name the user's files.
|
||||
let error: string | undefined;
|
||||
try {
|
||||
return await (tool.environment === "main" ?
|
||||
this.runInMain(tool.name as MainToolName, args, signal)
|
||||
: this.renderer.call(tool.name, args, signal));
|
||||
} catch (thrown) {
|
||||
error = isDapiError(thrown) ? thrown.code : "error";
|
||||
throw thrown;
|
||||
} finally {
|
||||
release();
|
||||
const client = session.server.getClientVersion();
|
||||
this.deps.onToolCall?.({
|
||||
tool: tool.name,
|
||||
client: client?.name,
|
||||
client_version: client?.version,
|
||||
ok: !error,
|
||||
error,
|
||||
duration_ms: Math.round(performance.now() - startedAt),
|
||||
});
|
||||
}
|
||||
});
|
||||
serveCatalog(session, (tool, args, signal) =>
|
||||
tool.environment === "main" ?
|
||||
this.runInMain(tool.name as MainToolName, args, signal)
|
||||
: this.renderer.call(tool.name, args, signal),
|
||||
);
|
||||
return session;
|
||||
}
|
||||
|
||||
private runInMain(name: MainToolName, args: unknown, signal: AbortSignal): Promise<unknown> {
|
||||
const ctx: MainContext = { signal, logs: this.deps.logs, version: this.deps.version, window: this.deps.window };
|
||||
const ctx: MainContext = { signal, logs: this.deps.logs, version: this.deps.version };
|
||||
// Each handler takes its own parsed args; the map's union type cannot
|
||||
// express that pairing, so the call site widens.
|
||||
return (mainHandlers[name] as (args: unknown, ctx: MainContext) => Promise<unknown>)(args, ctx);
|
||||
|
||||
@ -9,8 +9,6 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { JSON_SCHEMA_DIALECT, tools } from "@diffusionstudio/dapi";
|
||||
import { serveCatalog } from "./tools-session";
|
||||
|
||||
const CONTEXT = { rootDir: null, projectDir: null, currentTime: null, fontFamilies: [] };
|
||||
|
||||
let client: Client;
|
||||
const calls: Array<{ name: string; args: unknown }> = [];
|
||||
|
||||
@ -19,8 +17,8 @@ beforeAll(async () => {
|
||||
serveCatalog(session, async (tool, args) => {
|
||||
calls.push({ name: tool.name, args });
|
||||
switch (tool.name) {
|
||||
case "context":
|
||||
return CONTEXT;
|
||||
case "whoami":
|
||||
return { user: null };
|
||||
case "check":
|
||||
throw new Error("No project open — run open first");
|
||||
default:
|
||||
@ -56,9 +54,9 @@ describe("serveCatalog", () => {
|
||||
expect(JSON.stringify(bad.content)).toContain("limit");
|
||||
expect(calls.length).toBe(before);
|
||||
|
||||
const result = await client.callTool({ name: "context", arguments: {} });
|
||||
expect(result.structuredContent).toEqual(CONTEXT);
|
||||
expect(calls.at(-1)).toEqual({ name: "context", args: {} });
|
||||
const result = await client.callTool({ name: "whoami", arguments: {} });
|
||||
expect(result.structuredContent).toEqual({ user: null });
|
||||
expect(calls.at(-1)).toEqual({ name: "whoami", args: {} });
|
||||
});
|
||||
|
||||
it("returns a handler's failure as a readable error result, not a protocol error", async () => {
|
||||
|
||||
@ -6,9 +6,16 @@
|
||||
// canvas (renderer) and the edit writer (main). Types only, with no Node
|
||||
// imports, so the renderer's program can include it without Node's types.
|
||||
|
||||
import type { InspectValue, PropValue } from "@diffusionstudio/jsx";
|
||||
import type { InspectValue, PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";
|
||||
|
||||
export type { PropValue };
|
||||
export type { PropValue, SerializedAssetRef };
|
||||
|
||||
/**
|
||||
* A value an edit can carry: what a source spells as a literal, or a
|
||||
* `generate.*` declaration in its wire form, spelled as the call that
|
||||
* reproduces it (see `setProp`).
|
||||
*/
|
||||
export type EditValue = PropValue | SerializedAssetRef;
|
||||
|
||||
export interface SourceContext {
|
||||
/** Absolute path of the project folder. */
|
||||
@ -30,7 +37,7 @@ export interface SourceContext {
|
||||
export interface SourceSet {
|
||||
kind: "set";
|
||||
source: string;
|
||||
props: Record<string, PropValue>;
|
||||
props: Record<string, EditValue>;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
@ -47,7 +54,7 @@ export interface SourceInsert {
|
||||
source: string;
|
||||
parent: string;
|
||||
tag: string;
|
||||
props: Record<string, PropValue>;
|
||||
props: Record<string, EditValue>;
|
||||
before?: string;
|
||||
text?: string;
|
||||
}
|
||||
@ -87,7 +94,7 @@ export interface SourceRemove {
|
||||
* one in `ids`. The first iteration keeps the body's own names, so it carries
|
||||
* none.
|
||||
*/
|
||||
export type SourceIteration = Record<string, { props: Record<string, PropValue>; text?: string; pending?: string }>;
|
||||
export type SourceIteration = Record<string, { props: Record<string, EditValue>; text?: string; pending?: string }>;
|
||||
|
||||
/**
|
||||
* Replaces the `<For>`/`<Index>` around the element named by `source` with
|
||||
|
||||
@ -1,77 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The canvas shows an edit before the file has it, and an export and the next
|
||||
// open render the file: an edit the write left out would move back. So the
|
||||
// user wins — a prop is written over whatever the source held for it.
|
||||
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { applyEdits } from "./edit";
|
||||
|
||||
const FILE = "main.tsx";
|
||||
|
||||
let dir: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), "edit-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("applyEdits", () => {
|
||||
it("writes a prop over a literal and over an expression alike", async () => {
|
||||
await writeFile(
|
||||
join(dir, FILE),
|
||||
`const X = 100;\nexport default () => <video id="clip" x={X} y={20} rotation={ticker() * 2} />;\n`,
|
||||
);
|
||||
|
||||
const result = await applyEdits({ dir }, [
|
||||
{ kind: "set", source: `${FILE}:clip`, props: { x: 555, y: 42, rotation: 90 } },
|
||||
]);
|
||||
|
||||
expect(result.skipped).toEqual([]);
|
||||
const text = await readFile(join(dir, FILE), "utf8");
|
||||
expect(text).toContain(`<video id="clip" x={555} y={42} rotation={90} />`);
|
||||
// The constant is someone else's too, and stays.
|
||||
expect(text).toContain(`const X = 100;`);
|
||||
});
|
||||
|
||||
it("keeps a text's paint when what it says changes", async () => {
|
||||
await writeFile(join(dir, FILE), `export default () => <scene id="s"></scene>;\n`);
|
||||
|
||||
// The draw tool's insert: the text, then its paint under it.
|
||||
await applyEdits({ dir }, [
|
||||
{ kind: "insert", source: "pending#1", parent: `${FILE}:s`, tag: "text", props: {}, text: "Text" },
|
||||
{ kind: "insert", source: "pending#2", parent: "pending#1", tag: "solidPaint", props: { color: "#FFFFFF" } },
|
||||
]);
|
||||
const inserted = await readFile(join(dir, FILE), "utf8");
|
||||
const id = /<text id="([^"]+)"/.exec(inserted)![1];
|
||||
|
||||
// Then typing into it, once the insert has its name.
|
||||
const result = await applyEdits({ dir }, [{ kind: "set", source: `${FILE}:${id}`, props: {}, text: "Hello" }]);
|
||||
|
||||
expect(result.skipped).toEqual([]);
|
||||
const text = await readFile(join(dir, FILE), "utf8");
|
||||
expect(text).toMatch(/<text id="[^"]+">Hello\s*<solidPaint id="[^"]+" color="#FFFFFF" \/>\s*<\/text>/);
|
||||
});
|
||||
|
||||
it("replaces every part of what a text says, and only that", async () => {
|
||||
await writeFile(
|
||||
join(dir, FILE),
|
||||
`export default () => (\n <text id="t">\n Hello {name}!\n <solidPaint color="#FFFFFF" />\n {/* note */}\n </text>\n);\n`,
|
||||
);
|
||||
|
||||
const result = await applyEdits({ dir }, [{ kind: "set", source: `${FILE}:t`, props: {}, text: "Bye" }]);
|
||||
|
||||
expect(result.skipped).toEqual([]);
|
||||
const text = await readFile(join(dir, FILE), "utf8");
|
||||
expect(text).toContain(` <text id="t">\n Bye\n <solidPaint color="#FFFFFF" />\n {/* note */}\n </text>`);
|
||||
});
|
||||
});
|
||||
@ -9,11 +9,11 @@ import { join } from "node:path";
|
||||
|
||||
import { IndentationText, Project, SyntaxKind } from "ts-morph";
|
||||
|
||||
import { ID_ATTR, INSPECT_TAG, formatSource, isCompositionTag, isLoopTag, parseSource } from "@diffusionstudio/jsx";
|
||||
import { ID_ATTR, INSPECT_TAG, formatSource, isCompositionTag, isLoopTag, isSerializedAssetRef, isTransformType, parseSource } from "@diffusionstudio/jsx";
|
||||
|
||||
import { writeFileAtomic } from "./atomic";
|
||||
|
||||
import type { PropValue } from "@diffusionstudio/jsx";
|
||||
import type { PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";
|
||||
import type {
|
||||
ArrowFunction,
|
||||
FunctionExpression,
|
||||
@ -28,6 +28,7 @@ import type {
|
||||
|
||||
export type * from "./edit-types";
|
||||
import type {
|
||||
EditValue,
|
||||
SourceContext,
|
||||
SourceEdit,
|
||||
SourceInsert,
|
||||
@ -120,7 +121,8 @@ const round = (value: number): number => Math.round(value * 100) / 100;
|
||||
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
|
||||
|
||||
/** A prop value as the JavaScript that would have produced it. */
|
||||
function literalText(value: PropValue): string {
|
||||
function literalText(value: PropValue | SerializedAssetRef): string {
|
||||
if (isSerializedAssetRef(value)) return declarationText(value);
|
||||
if (typeof value === "string") return JSON.stringify(value);
|
||||
if (typeof value === "number") return String(round(value));
|
||||
if (typeof value === "boolean" || value === null) return String(value);
|
||||
@ -150,14 +152,46 @@ const initializerText = (value: PropValue): string =>
|
||||
? `"${value}"`
|
||||
: `{${literalText(value)}}`;
|
||||
|
||||
/**
|
||||
* A declaration's wire form as the call that reproduces it: `generate.<type>`
|
||||
* over its options, or `transform.<type>` over its input, with declared
|
||||
* inputs spelled as the nested calls they are.
|
||||
*/
|
||||
function declarationText(ref: SerializedAssetRef): string {
|
||||
const { type, ...options } = ref.$asset;
|
||||
if (isTransformType(type)) return `transform.${type}(${literalText((options as { input: EditValue }).input)})`;
|
||||
return `generate.${type}(${literalText(options as Record<string, PropValue>)})`;
|
||||
}
|
||||
|
||||
/** The namespaces a declaration is spelled with: what its file has to import. */
|
||||
function declarationImports(ref: SerializedAssetRef, names = new Set<string>()): Set<string> {
|
||||
const { type, ...options } = ref.$asset;
|
||||
names.add(isTransformType(type) ? "transform" : "generate");
|
||||
for (const value of Object.values(options)) {
|
||||
for (const input of Array.isArray(value) ? value : [value]) {
|
||||
if (isSerializedAssetRef(input)) declarationImports(input, names);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a prop onto a tag as one would write it: `muted`, not `muted={true}`,
|
||||
* and no attribute at all rather than `muted={false}`, since absence is what a
|
||||
* boolean prop's false reads as.
|
||||
* boolean prop's false reads as. A declaration is spelled as the call that
|
||||
* reproduces it — the caller makes sure its namespaces are imported (see
|
||||
* `ensureDeclarationImports`).
|
||||
*/
|
||||
function setProp(tag: JsxTag, name: string, value: PropValue): void {
|
||||
function setProp(tag: JsxTag, name: string, value: EditValue): void {
|
||||
const attribute = attributeOf(tag, name);
|
||||
|
||||
if (isSerializedAssetRef(value)) {
|
||||
const initializer = `{${declarationText(value)}}`;
|
||||
if (attribute) attribute.setInitializer(initializer);
|
||||
else tag.addAttribute({ name, initializer });
|
||||
return;
|
||||
}
|
||||
|
||||
if (value === true) {
|
||||
if (attribute) attribute.removeInitializer();
|
||||
else tag.addAttribute({ name });
|
||||
@ -173,6 +207,45 @@ function setProp(tag: JsxTag, name: string, value: PropValue): void {
|
||||
else tag.addAttribute({ name, initializer: initializerText(value) });
|
||||
}
|
||||
|
||||
/** Where `generate` and `transform` come from — the module every project authors against. */
|
||||
const DECLARATION_MODULE = "@diffusionstudio/jsx";
|
||||
|
||||
/**
|
||||
* Makes sure the namespaces a declaration is spelled with are in scope once
|
||||
* it has been written into the file: added to the module's existing import,
|
||||
* or as an import of their own after the last one — or above the first
|
||||
* statement, past the file's header comments, when there are no imports at
|
||||
* all. Idempotent.
|
||||
*/
|
||||
function ensureDeclarationImports(sourceFile: SourceFile, ref: SerializedAssetRef): void {
|
||||
for (const name of declarationImports(ref)) ensureNamedImport(sourceFile, name);
|
||||
}
|
||||
|
||||
function ensureNamedImport(sourceFile: SourceFile, name: string): void {
|
||||
const declarations = sourceFile.getImportDeclarations();
|
||||
const importable = declarations.find(
|
||||
(declaration) =>
|
||||
declaration.getModuleSpecifierValue() === DECLARATION_MODULE &&
|
||||
!declaration.isTypeOnly() &&
|
||||
!declaration.getNamespaceImport(),
|
||||
);
|
||||
|
||||
if (importable) {
|
||||
const named = importable.getNamedImports();
|
||||
if (named.some((specifier) => specifier.getName() === name && !specifier.getAliasNode())) return;
|
||||
importable.addNamedImport(name);
|
||||
return;
|
||||
}
|
||||
|
||||
const statement = `import { ${name} } from "${DECLARATION_MODULE}";`;
|
||||
const last = declarations.at(-1);
|
||||
if (last) sourceFile.insertText(last.getEnd(), `\n${statement}`);
|
||||
else {
|
||||
const first = sourceFile.getStatements()[0];
|
||||
sourceFile.insertText(first ? first.getStart() : 0, `${statement}\n\n`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Text content as JSX spells it: bare when JSX would read it back verbatim,
|
||||
* otherwise as a string expression (JSX collapses whitespace around line
|
||||
@ -184,10 +257,8 @@ function jsxText(text: string): string {
|
||||
|
||||
/**
|
||||
* Replaces what an element says between its tags; a self-closing one is opened
|
||||
* up around the new text. Only the text is replaced: the elements it holds
|
||||
* besides (its paint, a stroke, a range) stay, and so does everything outside
|
||||
* the body, so an element that says something else is otherwise the element
|
||||
* it was.
|
||||
* up around the new text. Everything outside the body keeps its bytes, so an
|
||||
* element that says something else is otherwise the element it was.
|
||||
*/
|
||||
function setText(sourceFile: SourceFile, tag: JsxTag, text: string): void {
|
||||
const element = elementOf(tag);
|
||||
@ -199,44 +270,7 @@ function setText(sourceFile: SourceFile, tag: JsxTag, text: string): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const ranges = element.getJsxChildren().filter(isSaid).map(saidRange);
|
||||
// Nothing said yet: it is said first, the way an insert spells it.
|
||||
if (!ranges.length) {
|
||||
if (content) sourceFile.insertText(element.getOpeningElement().getEnd(), content);
|
||||
return;
|
||||
}
|
||||
|
||||
// The first part says all of it and the rest say nothing. Later parts go
|
||||
// first, so the positions of the earlier ones still hold.
|
||||
for (const range of ranges.slice(1).reverse()) sourceFile.replaceText(range, "");
|
||||
sourceFile.replaceText(ranges[0]!, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a child of an element is part of what it says: text JSX keeps, or
|
||||
* an expression with no element in it. A comment (an expression with nothing
|
||||
* in it) says nothing.
|
||||
*/
|
||||
function isSaid(child: Node): boolean {
|
||||
if (child.isKind(SyntaxKind.JsxText)) return !child.containsOnlyTriviaWhiteSpaces();
|
||||
const expression = child.asKind(SyntaxKind.JsxExpression)?.getExpression();
|
||||
if (!expression) return false;
|
||||
return !JSX_KINDS.some((kind) => expression.isKind(kind) || expression.getFirstDescendantByKind(kind));
|
||||
}
|
||||
|
||||
const JSX_KINDS = [SyntaxKind.JsxElement, SyntaxKind.JsxSelfClosingElement, SyntaxKind.JsxFragment] as const;
|
||||
|
||||
/**
|
||||
* Where a part of what an element says is spelled. For text, that is without
|
||||
* the whitespace JSX drops around line breaks: the layout of the body is the
|
||||
* file's, not the text's.
|
||||
*/
|
||||
function saidRange(child: Node): [number, number] {
|
||||
if (!child.isKind(SyntaxKind.JsxText)) return [child.getStart(), child.getEnd()];
|
||||
const raw = child.getFullText();
|
||||
const leading = /^[ \t]*\n\s*/.exec(raw)?.[0].length ?? 0;
|
||||
const trailing = /\s*\n[ \t]*$/.exec(raw)?.[0].length ?? 0;
|
||||
return [child.getPos() + leading, child.getEnd() - trailing];
|
||||
sourceFile.replaceText([element.getOpeningElement().getEnd(), element.getClosingElement().getStart()], content);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -414,8 +448,14 @@ function reindent(text: string, from: string, to: string): string {
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/** Whether an expression is a value rather than a way of computing one. */
|
||||
/**
|
||||
* Whether an expression is a value rather than a way of computing one. A
|
||||
* declaration call over values is one too: it is what the writer spells a
|
||||
* declaration as, so it is an initializer the writer may also overwrite.
|
||||
*/
|
||||
function isLiteral(node: Node): boolean {
|
||||
if (isDeclarationCall(node)) return true;
|
||||
|
||||
if (
|
||||
node.isKind(SyntaxKind.StringLiteral) ||
|
||||
node.isKind(SyntaxKind.NumericLiteral) ||
|
||||
@ -449,11 +489,45 @@ function isLiteral(node: Node): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The namespaces a declaration call is made through. */
|
||||
const DECLARATION_NAMESPACES = new Set(["generate", "transform"]);
|
||||
|
||||
/**
|
||||
* A `generate.*` or `transform.*` call over literals — a nested declaration
|
||||
* among them. One whose argument computes anything is authored reactivity,
|
||||
* like any expression.
|
||||
*/
|
||||
function isDeclarationCall(node: Node): boolean {
|
||||
const call = node.asKind(SyntaxKind.CallExpression);
|
||||
const callee = call?.getExpression().asKind(SyntaxKind.PropertyAccessExpression);
|
||||
if (!call || !callee || !callee.getExpression().isKind(SyntaxKind.Identifier)) return false;
|
||||
if (!DECLARATION_NAMESPACES.has(callee.getExpression().getText())) return false;
|
||||
|
||||
const args = call.getArguments();
|
||||
return args.length === 1 && isLiteral(args[0]!);
|
||||
}
|
||||
|
||||
/**
|
||||
* A prop is only written back when the source holds a plain literal (or a
|
||||
* declaration the writer itself spells). Anything else — a signal, a prop of
|
||||
* the surrounding component, an expression — is someone's reactivity, and a
|
||||
* drag has no business overwriting it.
|
||||
*/
|
||||
function isWritable(attribute: JsxAttribute): boolean {
|
||||
const initializer = attribute.getInitializer();
|
||||
if (!initializer) return true;
|
||||
if (initializer.isKind(SyntaxKind.StringLiteral)) return true;
|
||||
if (!initializer.isKind(SyntaxKind.JsxExpression)) return false;
|
||||
|
||||
const expression = initializer.getExpression();
|
||||
return expression !== undefined && isLiteral(expression);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Files
|
||||
|
||||
/** Every project source file, project-relative and `/`-separated. */
|
||||
export async function sourceFiles(dir: string, prefix = ""): Promise<string[]> {
|
||||
async function sourceFiles(dir: string, prefix = ""): Promise<string[]> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(prefix ? join(dir, ...prefix.split("/")) : dir, { withFileTypes: true });
|
||||
@ -624,10 +698,10 @@ class SourceWriter {
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes prop values back into the JSX that produced them, over whatever
|
||||
* was there — a literal or an expression. An element that is written to and
|
||||
* has no id gets one, so that the next edit to renumber the file cannot
|
||||
* strand it.
|
||||
* Writes prop values back into the JSX that produced them. Props whose source
|
||||
* is an expression rather than a literal are reported as skipped and left
|
||||
* alone; an element that is written to and has no id gets one, so that the
|
||||
* next edit to renumber the file cannot strand it.
|
||||
*/
|
||||
public async applyEdits(edits: SourceEdit[]): Promise<WriteResult> {
|
||||
const skipped: string[] = [];
|
||||
@ -756,11 +830,14 @@ class SourceWriter {
|
||||
break;
|
||||
}
|
||||
|
||||
// Whatever the source held for it: the user wins. An expression
|
||||
// there (`x={MARGIN}`) is replaced by the value like a literal is —
|
||||
// the canvas already shows the edit, and an export and the next open
|
||||
// render the file, so a prop left as it was would move back.
|
||||
const attribute = attributeOf(tag, name);
|
||||
if (attribute && !isWritable(attribute)) {
|
||||
skipped.push(`${edit.source} (${name})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
setProp(tag, name, value);
|
||||
if (isSerializedAssetRef(value)) ensureDeclarationImports(sourceFile, value);
|
||||
wrote = true;
|
||||
}
|
||||
|
||||
@ -798,8 +875,8 @@ class SourceWriter {
|
||||
/**
|
||||
* Overwrites the initializer of an `@inspect`-annotated top-level const.
|
||||
* False when no top-level const of that name carries the annotation, or when
|
||||
* its initializer is not a literal anymore: the annotation promises the
|
||||
* inspector a value, and an expression there is no longer one.
|
||||
* its initializer is not a literal anymore — an expression there is authored
|
||||
* reactivity again, the same rule `isWritable` applies to a prop.
|
||||
*/
|
||||
private setVariable(sourceFile: SourceFile, edit: SourceVariable): boolean {
|
||||
for (const statement of sourceFile.getVariableStatements()) {
|
||||
@ -857,6 +934,7 @@ class SourceWriter {
|
||||
insertChild(sourceFile, parent, child, before);
|
||||
for (const [name, value] of Object.entries(edit.props)) {
|
||||
setProp(findTag(sourceFile, id)!, name, value);
|
||||
if (isSerializedAssetRef(value)) ensureDeclarationImports(sourceFile, value);
|
||||
}
|
||||
ids[edit.source] = formatSource(file, id);
|
||||
return true;
|
||||
@ -1096,6 +1174,7 @@ class SourceWriter {
|
||||
}
|
||||
for (const [name, value] of Object.entries(record.props)) {
|
||||
setProp(found(), name, value);
|
||||
if (isSerializedAssetRef(value)) ensureDeclarationImports(sourceFile, value);
|
||||
}
|
||||
|
||||
const element = elementOf(found());
|
||||
|
||||
@ -1,64 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Code editors a project folder can be opened in. A project is a folder of
|
||||
// JSX, so editing it by hand is a real way of working on it, and the app's
|
||||
// watcher puts whatever the editor saves on the canvas.
|
||||
|
||||
import { app } from "electron";
|
||||
import { execFile, spawn } from "node:child_process";
|
||||
import { isAbsolute } from "node:path";
|
||||
|
||||
export type EditorId = "vscode" | "cursor" | "zed";
|
||||
|
||||
export type EditorInfo = { id: EditorId; label: string };
|
||||
|
||||
/**
|
||||
* The editors offered, in menu order. Each is found by the URL scheme it
|
||||
* registers with the OS when installed: asking who handles it answers both
|
||||
* whether the editor is there and where, on macOS and Windows alike, without
|
||||
* knowing where anyone keeps their applications.
|
||||
*/
|
||||
const EDITORS: Array<EditorInfo & { protocol: string }> = [
|
||||
{ id: "vscode", label: "VS Code", protocol: "vscode://" },
|
||||
{ id: "cursor", label: "Cursor", protocol: "cursor://" },
|
||||
{ id: "zed", label: "Zed", protocol: "zed://" },
|
||||
];
|
||||
|
||||
/** Where the app handling `protocol` lives (the .app on macOS, the .exe on Windows), or null when none does. */
|
||||
async function handlerPath(protocol: string): Promise<string | null> {
|
||||
try {
|
||||
return (await app.getApplicationInfoForProtocol(protocol)).path || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The editors installed here, in menu order. */
|
||||
export async function installedEditors(): Promise<EditorInfo[]> {
|
||||
const found = await Promise.all(EDITORS.map(async (editor) => ((await handlerPath(editor.protocol)) ? editor : null)));
|
||||
return found.filter((editor) => editor !== null).map(({ id, label }) => ({ id, label }));
|
||||
}
|
||||
|
||||
/** Opens the folder `dir` in the editor `id`. */
|
||||
export async function openInEditor(id: EditorId, dir: string): Promise<void> {
|
||||
const editor = EDITORS.find((candidate) => candidate.id === id);
|
||||
if (!editor) throw new Error(`Unknown editor "${id}".`);
|
||||
if (!isAbsolute(dir)) throw new Error(`The folder must be an absolute path (got "${dir}").`);
|
||||
|
||||
const path = await handlerPath(editor.protocol);
|
||||
if (!path) throw new Error(`${editor.label} is not installed.`);
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
execFile("/usr/bin/open", ["-a", path, dir], (error) => (error ? reject(error) : resolve()));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Windows: the editor's own executable takes a folder to open, and outlives the app.
|
||||
const child = spawn(path, [dir], { detached: true, stdio: "ignore" });
|
||||
child.on("error", (error) => console.error(`[editors] could not start ${editor.label}:`, error));
|
||||
child.unref();
|
||||
}
|
||||
18
apps/desktop/src/headless.ts
Normal file
@ -0,0 +1,18 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Whether an agent has connected since launch. Once one has, the UI steps
|
||||
// back: file writes from tools are not echoed as edits, and the window may
|
||||
// stay hidden. Set by the MCP server on its first connection; read wherever
|
||||
// behaviour depends on who is driving.
|
||||
|
||||
let headless = false;
|
||||
|
||||
export function isHeadless(): boolean {
|
||||
return headless;
|
||||
}
|
||||
|
||||
export function enableHeadless(): void {
|
||||
headless = true;
|
||||
}
|
||||
@ -1,136 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Projects from before generation was removed are pointed at what their
|
||||
// declarations produced. The keys below are in the shape the generation code
|
||||
// wrote them: the request, defaults applied, inputs by asset id.
|
||||
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { migrateGenerations } from "./legacy-generations";
|
||||
|
||||
const FILE = "index.tsx";
|
||||
|
||||
const asset = (id: string, path: string, key?: string) => ({
|
||||
id,
|
||||
path,
|
||||
source: `assets/${path}`,
|
||||
type: "IMAGE",
|
||||
mimeType: "image/png",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
...(key ? { generation: { key, id: "run" } } : {}),
|
||||
});
|
||||
|
||||
const HERO_KEY = JSON.stringify({ type: "image", model: "flux", prompt: "A neon city", aspectRatio: "16:9", seed: 7, refIds: [] });
|
||||
const MOTION_KEY = JSON.stringify({ type: "video", model: "kling", prompt: "push in", aspectRatio: "16:9", duration: 5, audio: false, seed: 3, startFrameId: "hero01" });
|
||||
const UPSCALE_KEY = JSON.stringify({ type: "upscale", inputId: "photo1" });
|
||||
|
||||
const MANIFEST = {
|
||||
version: 1,
|
||||
folders: [],
|
||||
assets: [
|
||||
asset("hero01", "generated/A neon city.png", HERO_KEY),
|
||||
asset("motion", "generated/push in.mp4", MOTION_KEY),
|
||||
asset("photo1", "photos/me.png"),
|
||||
asset("upsc01", "generated/me (Upscaled).png", UPSCALE_KEY),
|
||||
asset("capt01", "generated/Captions 1.json", "transcript:v1:intro:123"),
|
||||
asset("capt02", "generated/Captions 2.json", "transcript:v1:outro:0"),
|
||||
// A failed generation's record: no bytes, so no answer.
|
||||
{ id: "fail01", path: "generated/a fox", type: "IMAGE", createdAt: "2026-01-01", generation: { key: "x" }, state: "error" },
|
||||
],
|
||||
};
|
||||
|
||||
let dir: string;
|
||||
const written: string[] = [];
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), "legacy-generations-test-"));
|
||||
written.length = 0;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function migrate(source: string, manifest: unknown = MANIFEST): Promise<string> {
|
||||
await writeFile(join(dir, FILE), source);
|
||||
await migrateGenerations({ dir, onWrite: (file) => written.push(file) }, manifest);
|
||||
return readFile(join(dir, FILE), "utf8");
|
||||
}
|
||||
|
||||
describe("migrateGenerations", () => {
|
||||
it("points declarations at the assets they made, chains and consts included, and drops the import", async () => {
|
||||
const text = await migrate(`import { For } from "solid-js";
|
||||
import { generate, transform } from "@diffusionstudio/jsx";
|
||||
|
||||
const hero = generate.image({ prompt: "A neon city", aspectRatio: "16:9", seed: 7 });
|
||||
const motion = generate.video({ prompt: "push in", startFrame: hero, seed: 3 });
|
||||
|
||||
export default () => (
|
||||
<scene id="intro">
|
||||
<video id="a" src={motion} />
|
||||
<image id="b" src={transform.upscale("photos/me.png")} />
|
||||
</scene>
|
||||
);
|
||||
`);
|
||||
|
||||
expect(text).toContain(`const hero = "generated/A neon city.png";`);
|
||||
expect(text).toContain(`const motion = "generated/push in.mp4";`);
|
||||
expect(text).toContain(`<image id="b" src="generated/me (Upscaled).png" />`);
|
||||
expect(text).not.toContain("@diffusionstudio/jsx");
|
||||
expect(text).toContain(`import { For } from "solid-js";`);
|
||||
expect(written).toEqual([FILE]);
|
||||
});
|
||||
|
||||
it("keeps a declaration nothing matches beside an empty source, so the project still loads", async () => {
|
||||
const text = await migrate(`import { generate } from "@diffusionstudio/jsx";
|
||||
export default () => <image id="c" src={generate.image({ prompt: "never made", seed: 1 })} />;
|
||||
`);
|
||||
|
||||
expect(text).toContain(`src={"" /* no generated asset matched; generation was removed: generate.image({ prompt: "never made", seed: 1 }) */}`);
|
||||
expect(text).not.toContain("import { generate }");
|
||||
});
|
||||
|
||||
it("does not take a key whose recorded fields differ from what the call spells", async () => {
|
||||
const text = await migrate(`import { generate } from "@diffusionstudio/jsx";
|
||||
export default () => <image id="c" src={generate.image({ prompt: "A neon city", seed: 8 })} />;
|
||||
`);
|
||||
|
||||
expect(text).not.toContain("A neon city.png");
|
||||
});
|
||||
|
||||
it("gives a src-less caption the transcript of its scene and seed", async () => {
|
||||
const text = await migrate(`export default () => (
|
||||
<stage>
|
||||
<scene id="intro"><captions id="c1" preset="classic" seed={123} /></scene>
|
||||
<scene id="outro"><Captions id="c2" /></scene>
|
||||
<scene id="other"><captions id="c3" /></scene>
|
||||
</stage>
|
||||
);
|
||||
`);
|
||||
|
||||
expect(text).toContain(`<captions id="c1" preset="classic" src="generated/Captions 1.json" />`);
|
||||
expect(text).toContain(`<Captions src="generated/Captions 2.json" id="c2" />`);
|
||||
// No transcript was ever made for this scene: left as it was.
|
||||
expect(text).toContain(`<captions id="c3" />`);
|
||||
});
|
||||
|
||||
it("writes nothing to a migrated project, or without a readable library", async () => {
|
||||
const source = `import { generate } from "@diffusionstudio/jsx";
|
||||
export default () => <image id="c" src={generate.image({ prompt: "A neon city", seed: 7 })} />;
|
||||
`;
|
||||
expect(await migrate(source, null)).toBe(source);
|
||||
expect(written).toEqual([]);
|
||||
|
||||
const migrated = await migrate(source);
|
||||
expect(migrated).toContain(`src="generated/A neon city.png"`);
|
||||
written.length = 0;
|
||||
|
||||
await migrateGenerations({ dir, onWrite: (file) => written.push(file) }, MANIFEST);
|
||||
expect(written).toEqual([]);
|
||||
});
|
||||
});
|
||||
@ -1,509 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
/**
|
||||
* A one-time rewrite of projects written before generation was removed from
|
||||
* the JSX. Those projects declare assets with `generate.*` / `transform.*`
|
||||
* calls and caption scenes with a `<captions>` that has no `src`; neither
|
||||
* loads any more. What they produced is still in the library: every asset a
|
||||
* generation landed as carries its `generation.key` in `assets.yml`, the
|
||||
* request as it was sent. So each declaration is matched against those keys
|
||||
* and replaced by the library path of the asset it made, and each `src`-less
|
||||
* `<captions>` gets the transcript its scene was given.
|
||||
*
|
||||
* Runs before every compile and writes nothing to a project with nothing left
|
||||
* to migrate. A declaration that matches no asset is replaced by an empty
|
||||
* source with the call kept beside it in a comment, so the project loads and
|
||||
* nothing the user wrote is lost. Delete this file once projects from before
|
||||
* the removal no longer need opening.
|
||||
*/
|
||||
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { Project, SyntaxKind } from "ts-morph";
|
||||
|
||||
import { ID_ATTR } from "@diffusionstudio/jsx";
|
||||
|
||||
import { writeFileAtomic } from "./atomic";
|
||||
import { sourceFiles } from "./edit";
|
||||
|
||||
import type { CallExpression, JsxOpeningElement, JsxSelfClosingElement, Node, SourceFile } from "ts-morph";
|
||||
import type { SourceContext } from "./edit-types";
|
||||
|
||||
/** The module the declarations were imported from. */
|
||||
const JSX_MODULE = "@diffusionstudio/jsx";
|
||||
|
||||
/** Defaults the generation applied, and so baked into its key, when the call left them out. */
|
||||
const DEFAULTS: Record<string, Record<string, unknown>> = {
|
||||
image: { aspectRatio: "16:9" },
|
||||
video: { aspectRatio: "16:9", duration: 5, audio: false },
|
||||
};
|
||||
|
||||
/**
|
||||
* Fields whose defaults lived in the app's model lists rather than here: when
|
||||
* the call leaves one out, any value in the key is taken to be the default.
|
||||
*/
|
||||
const FREE_WHEN_OMITTED = new Set(["model", "voice"]);
|
||||
|
||||
type Namespace = "generate" | "transform";
|
||||
|
||||
/** A `generate.*` / `transform.*` call, with its argument read as a value. */
|
||||
interface Declaration {
|
||||
namespace: Namespace;
|
||||
type: string;
|
||||
node: CallExpression;
|
||||
argument: unknown;
|
||||
}
|
||||
|
||||
/** A value the source computes rather than spells; a declaration over one cannot be matched. */
|
||||
const UNKNOWN = Symbol("unknown");
|
||||
|
||||
interface ManifestEntry {
|
||||
id: string;
|
||||
path: string;
|
||||
key?: string;
|
||||
}
|
||||
|
||||
/** What the library knows: entries newest first, as the manifest lists them. */
|
||||
class Library {
|
||||
private readonly entries: ManifestEntry[];
|
||||
|
||||
public constructor(entries: ManifestEntry[]) {
|
||||
this.entries = entries;
|
||||
}
|
||||
|
||||
/** The id of the asset an input named: an id, or a library path. */
|
||||
public idOf(input: string): string | undefined {
|
||||
const path = normalizePath(input);
|
||||
return this.entries.find((entry) => entry.id === input || entry.path === path)?.id;
|
||||
}
|
||||
|
||||
/** The newest asset whose generation key, parsed, satisfies `matches`. */
|
||||
public generated(matches: (key: Record<string, unknown>) => boolean): ManifestEntry | undefined {
|
||||
for (const entry of this.entries) {
|
||||
if (!entry.key?.startsWith("{")) continue;
|
||||
try {
|
||||
const key = JSON.parse(entry.key) as unknown;
|
||||
if (key && typeof key === "object" && matches(key as Record<string, unknown>)) return entry;
|
||||
} catch {
|
||||
// Not a key this migration knows how to read.
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** The transcript a scene was given under `key`. */
|
||||
public byKey(key: string): ManifestEntry | undefined {
|
||||
return this.entries.find((entry) => entry.key === key);
|
||||
}
|
||||
}
|
||||
|
||||
/** Library entries that have bytes and a generation key; anything else is no answer. */
|
||||
function readEntries(manifest: unknown): ManifestEntry[] {
|
||||
const assets = (manifest as { assets?: unknown } | null)?.assets;
|
||||
if (!Array.isArray(assets)) return [];
|
||||
|
||||
return assets.flatMap((record): ManifestEntry[] => {
|
||||
if (!record || typeof record !== "object") return [];
|
||||
const r = record as Record<string, unknown>;
|
||||
if (typeof r.id !== "string" || typeof r.path !== "string" || typeof r.source !== "string") return [];
|
||||
const generation = r.generation as { key?: unknown } | undefined;
|
||||
const key = typeof generation?.key === "string" ? generation.key : undefined;
|
||||
return [{ id: r.id, path: normalizePath(r.path), key }];
|
||||
});
|
||||
}
|
||||
|
||||
const normalizePath = (path: string): string =>
|
||||
path.replace(/\\/g, "/").split("/").filter((part) => part && part !== ".").join("/");
|
||||
|
||||
/** Whether the project might hold anything to migrate; saves parsing the rest. */
|
||||
const mayNeedMigration = (text: string): boolean => text.includes(JSX_MODULE) || /<captions\b/i.test(text);
|
||||
|
||||
/**
|
||||
* Rewrites every source file of the project that still declares generations
|
||||
* or `src`-less captions. Returns the project-relative files it wrote.
|
||||
*/
|
||||
export async function migrateGenerations(context: SourceContext, manifest: unknown): Promise<string[]> {
|
||||
// Without a readable library every declaration would look unmatched.
|
||||
if (!Array.isArray((manifest as { assets?: unknown } | null)?.assets)) return [];
|
||||
|
||||
const library = new Library(readEntries(manifest));
|
||||
const project = new Project({ useInMemoryFileSystem: true, skipLoadingLibFiles: true });
|
||||
const written: string[] = [];
|
||||
|
||||
for (const path of await sourceFiles(context.dir)) {
|
||||
const absolute = join(context.dir, ...path.split("/"));
|
||||
let text: string;
|
||||
try {
|
||||
text = await readFile(absolute, "utf8");
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (!mayNeedMigration(text)) continue;
|
||||
|
||||
const next = migrateText(project, path, text, library);
|
||||
if (next === text) continue;
|
||||
|
||||
context.onWrite?.(path, next);
|
||||
await writeFileAtomic(absolute, next);
|
||||
written.push(path);
|
||||
}
|
||||
|
||||
if (written.length) console.log(`[projects] migrated generated assets in ${written.join(", ")}`);
|
||||
return written;
|
||||
}
|
||||
|
||||
/** The file's text with its declarations and captions migrated; the same text when there is nothing to do. */
|
||||
function migrateText(project: Project, path: string, text: string, library: Library): string {
|
||||
const sourceFile = project.createSourceFile(`/${path}`, text, { overwrite: true });
|
||||
try {
|
||||
// A file mid-edit is not one to rewrite.
|
||||
if (project.getProgram().getSyntacticDiagnostics(sourceFile).length) return text;
|
||||
|
||||
const edits = [...declarationEdits(sourceFile, library), ...captionEdits(sourceFile, library)];
|
||||
if (!edits.length) return text;
|
||||
|
||||
let next = text;
|
||||
for (const edit of outermost(edits).sort((a, b) => b.start - a.start)) {
|
||||
next = next.slice(0, edit.start) + edit.text + next.slice(edit.end);
|
||||
}
|
||||
return dropUnusedImports(project, path, next);
|
||||
} finally {
|
||||
project.removeSourceFile(sourceFile);
|
||||
}
|
||||
}
|
||||
|
||||
interface TextEdit {
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** Edits not inside another: replacing an outer call takes the calls inside it along. */
|
||||
function outermost(edits: TextEdit[]): TextEdit[] {
|
||||
return edits.filter((edit) => !edits.some((other) => other !== edit
|
||||
&& other.start <= edit.start && edit.end <= other.end
|
||||
&& (other.start !== edit.start || other.end !== edit.end)));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Declarations
|
||||
|
||||
/** The local names `generate` and `transform` were imported under. */
|
||||
function namespaces(sourceFile: SourceFile): Map<string, Namespace> {
|
||||
const names = new Map<string, Namespace>();
|
||||
for (const declaration of sourceFile.getImportDeclarations()) {
|
||||
if (declaration.getModuleSpecifierValue() !== JSX_MODULE) continue;
|
||||
for (const specifier of declaration.getNamedImports()) {
|
||||
const imported = specifier.getName();
|
||||
if (imported !== "generate" && imported !== "transform") continue;
|
||||
names.set(specifier.getAliasNode()?.getText() ?? imported, imported);
|
||||
}
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function declarationEdits(sourceFile: SourceFile, library: Library): TextEdit[] {
|
||||
const names = namespaces(sourceFile);
|
||||
if (!names.size) return [];
|
||||
|
||||
const declarations = new Map<CallExpression, Declaration>();
|
||||
const read = (node: Node, seen: Set<Node>): unknown => readValue(node, names, declarations, seen);
|
||||
|
||||
for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
|
||||
read(call, new Set());
|
||||
}
|
||||
|
||||
const paths = new Map<Declaration, string | undefined>();
|
||||
const resolve = (declaration: Declaration): string | undefined => {
|
||||
if (!paths.has(declaration)) paths.set(declaration, match(declaration, library, resolve));
|
||||
return paths.get(declaration);
|
||||
};
|
||||
|
||||
return [...declarations.values()].map((declaration) => {
|
||||
const path = resolve(declaration);
|
||||
return replacement(declaration.node, path, path === undefined ? declaration.node.getText() : undefined);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A node read as the value it spells: literals, arrays, object literals, a
|
||||
* const it names (followed in this file), or a declaration. `UNKNOWN` for
|
||||
* anything the source computes.
|
||||
*/
|
||||
function readValue(
|
||||
node: Node,
|
||||
names: Map<string, Namespace>,
|
||||
declarations: Map<CallExpression, Declaration>,
|
||||
seen: Set<Node>,
|
||||
): unknown {
|
||||
const read = (child: Node): unknown => readValue(child, names, declarations, seen);
|
||||
|
||||
if (node.isKind(SyntaxKind.ParenthesizedExpression)) return read(node.getExpression());
|
||||
if (node.isKind(SyntaxKind.AsExpression) || node.isKind(SyntaxKind.SatisfiesExpression)) return read(node.getExpression());
|
||||
if (node.isKind(SyntaxKind.StringLiteral) || node.isKind(SyntaxKind.NoSubstitutionTemplateLiteral)) return node.getLiteralValue();
|
||||
if (node.isKind(SyntaxKind.NumericLiteral)) return node.getLiteralValue();
|
||||
if (node.isKind(SyntaxKind.TrueKeyword)) return true;
|
||||
if (node.isKind(SyntaxKind.FalseKeyword)) return false;
|
||||
if (node.isKind(SyntaxKind.NullKeyword)) return null;
|
||||
if (node.isKind(SyntaxKind.Identifier) && node.getText() === "undefined") return undefined;
|
||||
|
||||
if (node.isKind(SyntaxKind.PrefixUnaryExpression) && node.getOperatorToken() === SyntaxKind.MinusToken) {
|
||||
const operand = read(node.getOperand());
|
||||
return typeof operand === "number" ? -operand : UNKNOWN;
|
||||
}
|
||||
|
||||
if (node.isKind(SyntaxKind.ArrayLiteralExpression)) {
|
||||
const items = node.getElements().map(read);
|
||||
return items.includes(UNKNOWN) ? UNKNOWN : items;
|
||||
}
|
||||
|
||||
if (node.isKind(SyntaxKind.ObjectLiteralExpression)) {
|
||||
const object: Record<string, unknown> = {};
|
||||
for (const property of node.getProperties()) {
|
||||
if (property.isKind(SyntaxKind.PropertyAssignment)) {
|
||||
const name = property.getNameNode();
|
||||
if (name.isKind(SyntaxKind.ComputedPropertyName)) return UNKNOWN;
|
||||
const key = name.isKind(SyntaxKind.StringLiteral) ? name.getLiteralValue() : name.getText();
|
||||
object[key] = read(property.getInitializerOrThrow());
|
||||
} else if (property.isKind(SyntaxKind.ShorthandPropertyAssignment)) {
|
||||
object[property.getName()] = read(property.getNameNode());
|
||||
} else {
|
||||
return UNKNOWN;
|
||||
}
|
||||
}
|
||||
return Object.values(object).includes(UNKNOWN) ? UNKNOWN : object;
|
||||
}
|
||||
|
||||
// A const, followed to its initializer once: a cycle reads as unknown.
|
||||
if (node.isKind(SyntaxKind.Identifier)) {
|
||||
const initializer = constInitializer(node);
|
||||
if (!initializer || seen.has(initializer)) return UNKNOWN;
|
||||
seen.add(initializer);
|
||||
return read(initializer);
|
||||
}
|
||||
|
||||
if (node.isKind(SyntaxKind.CallExpression)) {
|
||||
const known = declarations.get(node);
|
||||
if (known) return known;
|
||||
|
||||
const callee = node.getExpression().asKind(SyntaxKind.PropertyAccessExpression);
|
||||
const namespace = callee && names.get(callee.getExpression().getText());
|
||||
if (!callee || !namespace || !callee.getExpression().isKind(SyntaxKind.Identifier)) return UNKNOWN;
|
||||
|
||||
const [argument] = node.getArguments();
|
||||
const declaration: Declaration = {
|
||||
namespace,
|
||||
type: callee.getName(),
|
||||
node,
|
||||
argument: argument ? read(argument) : UNKNOWN,
|
||||
};
|
||||
declarations.set(node, declaration);
|
||||
return declaration;
|
||||
}
|
||||
|
||||
return UNKNOWN;
|
||||
}
|
||||
|
||||
/** The initializer of the top-level or block-scoped `const` an identifier names, in its own file. */
|
||||
function constInitializer(identifier: Node): Node | undefined {
|
||||
const symbol = identifier.getSymbol();
|
||||
const declaration = symbol?.getDeclarations()[0]?.asKind(SyntaxKind.VariableDeclaration);
|
||||
if (!declaration || declaration.getVariableStatement()?.getDeclarationKind() !== "const") return undefined;
|
||||
if (!declaration.getNameNode().isKind(SyntaxKind.Identifier)) return undefined;
|
||||
return declaration.getInitializer();
|
||||
}
|
||||
|
||||
const isDeclaration = (value: unknown): value is Declaration =>
|
||||
typeof value === "object" && value !== null && "namespace" in value && "node" in value;
|
||||
|
||||
/**
|
||||
* The library path of the asset a declaration made, or undefined when no
|
||||
* generation key matches it. Inputs are matched first, by id, which is how
|
||||
* the key recorded them.
|
||||
*/
|
||||
function match(
|
||||
declaration: Declaration,
|
||||
library: Library,
|
||||
resolve: (declaration: Declaration) => string | undefined,
|
||||
): string | undefined {
|
||||
const idOf = (input: unknown): string | undefined => {
|
||||
if (typeof input === "string") return library.idOf(input);
|
||||
if (isDeclaration(input)) {
|
||||
const path = resolve(input);
|
||||
return path === undefined ? undefined : library.idOf(path);
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const { type, argument } = declaration;
|
||||
|
||||
if (declaration.namespace === "transform") {
|
||||
const inputId = idOf(argument);
|
||||
if (inputId === undefined) return undefined;
|
||||
return library.generated((key) => key.type === type && key.inputId === inputId && Object.keys(key).length === 2)?.path;
|
||||
}
|
||||
|
||||
if (!argument || typeof argument !== "object" || isDeclaration(argument) || Array.isArray(argument)) return undefined;
|
||||
const options = argument as Record<string, unknown>;
|
||||
if (typeof options.prompt !== "string") return undefined;
|
||||
|
||||
// What the key must hold, field by field; `undefined` means it must not hold the field.
|
||||
const expected: Record<string, unknown> = { type, ...DEFAULTS[type] };
|
||||
for (const [name, value] of Object.entries(options)) {
|
||||
if (name === "refs" || name === "startFrame" || name === "endFrame") continue;
|
||||
expected[name] = value;
|
||||
}
|
||||
expected.seed = options.seed;
|
||||
|
||||
switch (type) {
|
||||
case "image": {
|
||||
const refs = Array.isArray(options.refs) ? options.refs : [];
|
||||
const refIds = refs.map(idOf);
|
||||
if (refIds.includes(undefined)) return undefined;
|
||||
expected.refIds = refIds;
|
||||
break;
|
||||
}
|
||||
case "video": {
|
||||
for (const [option, field] of [["startFrame", "startFrameId"], ["endFrame", "endFrameId"]] as const) {
|
||||
if (options[option] === undefined) {
|
||||
expected[field] = undefined;
|
||||
continue;
|
||||
}
|
||||
const id = idOf(options[option]);
|
||||
if (id === undefined) return undefined;
|
||||
expected[field] = id;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "audio":
|
||||
expected.duration = options.duration;
|
||||
break;
|
||||
case "voice":
|
||||
break;
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return library.generated((key) => Object.entries(expected).every(([name, value]) => {
|
||||
if (value === undefined) return FREE_WHEN_OMITTED.has(name) || !(name in key);
|
||||
return JSON.stringify(key[name]) === JSON.stringify(value);
|
||||
}))?.path;
|
||||
}
|
||||
|
||||
/**
|
||||
* The edit putting `path` where the call was: an attribute's `{call}` becomes
|
||||
* `"path"`, anything else the string literal. With no path, an empty source
|
||||
* stands in and the call is kept beside it in a comment.
|
||||
*/
|
||||
function replacement(call: CallExpression, path: string | undefined, unmatched?: string): TextEdit {
|
||||
const comment = unmatched === undefined
|
||||
? ""
|
||||
: ` /* no generated asset matched; generation was removed: ${unmatched.replace(/\*\//g, "* /")} */`;
|
||||
const literal = JSON.stringify(path ?? "");
|
||||
|
||||
const expression = call.getParent()?.asKind(SyntaxKind.JsxExpression);
|
||||
if (expression?.getParent()?.isKind(SyntaxKind.JsxAttribute)) {
|
||||
if (!comment && path !== undefined && !/["&\p{Cc}\u2028\u2029]/u.test(path)) {
|
||||
return { start: expression.getStart(), end: expression.getEnd(), text: literal };
|
||||
}
|
||||
return { start: call.getStart(), end: call.getEnd(), text: literal + comment };
|
||||
}
|
||||
|
||||
return { start: call.getStart(), end: call.getEnd(), text: literal + comment };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Captions
|
||||
|
||||
type JsxTag = JsxOpeningElement | JsxSelfClosingElement;
|
||||
|
||||
const lower = (tag: JsxTag): string => tag.getTagNameNode().getText().toLowerCase();
|
||||
|
||||
const idOf = (tag: JsxTag): string | undefined =>
|
||||
tag.getAttribute(ID_ATTR)?.asKind(SyntaxKind.JsxAttribute)?.getInitializer()?.asKind(SyntaxKind.StringLiteral)?.getLiteralValue();
|
||||
|
||||
/**
|
||||
* A `<captions>` without a `src` used to transcribe its scene, keyed by the
|
||||
* scene's id and the caption's `seed`. The transcript is in the library under
|
||||
* that key; the caption is pointed at it and loses the `seed`.
|
||||
*/
|
||||
function captionEdits(sourceFile: SourceFile, library: Library): TextEdit[] {
|
||||
const edits: TextEdit[] = [];
|
||||
const tags: JsxTag[] = [
|
||||
...sourceFile.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement),
|
||||
...sourceFile.getDescendantsOfKind(SyntaxKind.JsxOpeningElement),
|
||||
];
|
||||
|
||||
for (const tag of tags) {
|
||||
if (lower(tag) !== "captions") continue;
|
||||
const attributes = tag.getAttributes();
|
||||
if (tag.getAttribute("src") || attributes.some((attribute) => attribute.isKind(SyntaxKind.JsxSpreadAttribute))) continue;
|
||||
|
||||
const sceneId = enclosingSceneId(tag);
|
||||
if (sceneId === undefined) continue;
|
||||
|
||||
const seedAttribute = tag.getAttribute("seed")?.asKind(SyntaxKind.JsxAttribute);
|
||||
let seed = 0;
|
||||
if (seedAttribute) {
|
||||
const value = seedAttribute.getInitializer()?.asKind(SyntaxKind.JsxExpression)?.getExpression();
|
||||
const literal = value?.asKind(SyntaxKind.NumericLiteral)?.getLiteralValue();
|
||||
if (literal === undefined) continue;
|
||||
seed = literal;
|
||||
}
|
||||
|
||||
const transcript = library.byKey(`transcript:v1:${sceneId}:${seed}`);
|
||||
if (!transcript) continue;
|
||||
|
||||
const src = `src=${JSON.stringify(transcript.path)}`;
|
||||
if (seedAttribute) {
|
||||
edits.push({ start: seedAttribute.getStart(), end: seedAttribute.getEnd(), text: src });
|
||||
} else {
|
||||
const at = tag.getTagNameNode().getEnd();
|
||||
edits.push({ start: at, end: at, text: ` ${src}` });
|
||||
}
|
||||
}
|
||||
|
||||
return edits;
|
||||
}
|
||||
|
||||
/** The id of the `<scene>` element a tag sits inside, in the same JSX tree. */
|
||||
function enclosingSceneId(tag: JsxTag): string | undefined {
|
||||
for (const ancestor of tag.getAncestors()) {
|
||||
const opening = ancestor.asKind(SyntaxKind.JsxElement)?.getOpeningElement();
|
||||
if (opening && lower(opening) === "scene") return idOf(opening);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Imports
|
||||
|
||||
/** Takes `generate` / `transform` out of the imports once nothing uses them. */
|
||||
function dropUnusedImports(project: Project, path: string, text: string): string {
|
||||
const sourceFile = project.createSourceFile(`/${path}`, text, { overwrite: true });
|
||||
try {
|
||||
for (const declaration of sourceFile.getImportDeclarations()) {
|
||||
if (declaration.getModuleSpecifierValue() !== JSX_MODULE) continue;
|
||||
let removed = false;
|
||||
for (const specifier of declaration.getNamedImports()) {
|
||||
const name = specifier.getName();
|
||||
if (name !== "generate" && name !== "transform") continue;
|
||||
const local = specifier.getAliasNode()?.getText() ?? name;
|
||||
const used = sourceFile.getDescendantsOfKind(SyntaxKind.Identifier)
|
||||
.some((identifier) => identifier.getText() === local && !identifier.getFirstAncestorByKind(SyntaxKind.ImportDeclaration));
|
||||
if (used) continue;
|
||||
specifier.remove();
|
||||
removed = true;
|
||||
}
|
||||
// Only an import this emptied goes; one that imported nothing by name was never ours.
|
||||
if (removed && !declaration.getNamedImports().length && !declaration.getDefaultImport() && !declaration.getNamespaceImport()) {
|
||||
declaration.remove();
|
||||
}
|
||||
}
|
||||
return sourceFile.getFullText();
|
||||
} finally {
|
||||
project.removeSourceFile(sourceFile);
|
||||
}
|
||||
}
|
||||
@ -12,8 +12,6 @@
|
||||
import type { LogEntry, ScreenshotResult } from "@diffusionstudio/dapi";
|
||||
import type { SourceEdit, WriteResult } from "./edit-types";
|
||||
import type { AgentId } from "./mcp-config";
|
||||
import type { EditorId, EditorInfo } from "./editors";
|
||||
import type { MissingProjectChoice, SaveAction } from "./projects";
|
||||
|
||||
export const MAIN_WIRE = {
|
||||
REQUEST: "main:request",
|
||||
@ -32,33 +30,24 @@ export const MAIN_CHANNELS = {
|
||||
// Renderer→Main requests
|
||||
APP_OPEN_EXTERNAL: "app:open-external",
|
||||
APP_SHOW_IN_FOLDER: "app:show-in-folder",
|
||||
APP_EDITORS_LIST: "app:editors-list",
|
||||
APP_OPEN_IN_EDITOR: "app:open-in-editor",
|
||||
ANALYTICS_CONFIGURE: "analytics:configure",
|
||||
AUTH_GET_PENDING_CALLBACK: "auth:get-pending-callback",
|
||||
CHECKOUT_GET_PENDING_CALLBACK: "checkout:get-pending-callback",
|
||||
WINDOW_IS_FULLSCREEN: "window:is-fullscreen",
|
||||
WINDOW_SET_COLOR_MODE: "window:set-color-mode",
|
||||
WINDOW_CAPTURE: "window:capture",
|
||||
WINDOW_SET_BUSY: "window:set-busy",
|
||||
WINDOW_SHOW: "window:show",
|
||||
CLIPBOARD_PATHS: "clipboard:paths",
|
||||
FILE_TRANSFER: "file:transfer",
|
||||
FILE_WRITE_OPEN: "file:write-open",
|
||||
FILE_WRITE_CHUNK: "file:write-chunk",
|
||||
FILE_WRITE_CLOSE: "file:write-close",
|
||||
FILE_WRITE_ABORT: "file:write-abort",
|
||||
LOGS_GET: "logs:get",
|
||||
PROJECTS_PICK_ROOT: "projects:pick-root",
|
||||
PROJECTS_PICK_FOLDER: "projects:pick-folder",
|
||||
PROJECTS_DEFAULT_ROOT: "projects:default-root",
|
||||
PROJECTS_SCAN: "projects:scan",
|
||||
PROJECTS_GET: "projects:get",
|
||||
PROJECTS_INIT: "projects:init",
|
||||
PROJECTS_RESOLVE: "projects:resolve",
|
||||
PROJECTS_FIND_MOVED: "projects:find-moved",
|
||||
PROJECTS_ASK_MISSING: "projects:ask-missing",
|
||||
PROJECTS_CREATE: "projects:create",
|
||||
PROJECTS_PICK_SAVE: "projects:pick-save",
|
||||
PROJECTS_SAVE: "projects:save",
|
||||
PROJECTS_MOVE: "projects:move",
|
||||
PROJECTS_RENAME: "projects:rename",
|
||||
PROJECTS_DUPLICATE: "projects:duplicate",
|
||||
PROJECTS_DELETE: "projects:delete",
|
||||
@ -100,7 +89,7 @@ export type ProjectInfo = {
|
||||
* since — `PROJECTS_RESOLVE` is what gives one out.
|
||||
*/
|
||||
id: string;
|
||||
/** Folder name. The user can move or rename it, so it is not the identity. */
|
||||
/** Folder name. Renaming the project moves it, so it is not the identity. */
|
||||
name: string;
|
||||
/** Human name from package.json `displayName` (falls back to the folder name). */
|
||||
displayName: string;
|
||||
@ -112,11 +101,6 @@ export type ProjectInfo = {
|
||||
modifiedAt: string;
|
||||
/** birthtime of the folder, ISO string. */
|
||||
createdAt: string;
|
||||
/**
|
||||
* Whether the folder is a draft's: in the app's drafts folder, named after
|
||||
* the id, until the user saves it somewhere of their choosing.
|
||||
*/
|
||||
draft: boolean;
|
||||
};
|
||||
|
||||
export type CompileResult =
|
||||
@ -124,8 +108,6 @@ export type CompileResult =
|
||||
|
||||
export type { SourceEdit, WriteResult };
|
||||
export type { AgentId };
|
||||
export type { EditorId, EditorInfo };
|
||||
export type { MissingProjectChoice };
|
||||
|
||||
// One agent the settings page lists: whether it is set up on this machine,
|
||||
// whether its config already carries the app's MCP entry, and — for the
|
||||
@ -153,10 +135,10 @@ export type McpApplyResult = {
|
||||
failures: { id: AgentId; error: string }[];
|
||||
};
|
||||
|
||||
// Where the `diffusion` command stands. `managed` means what is there is a
|
||||
// Where the `dapi` command stands. `managed` means what is there is a
|
||||
// symlink (the app's own, or the dev workflow's Homebrew link), which
|
||||
// "Uninstall" can remove; `available` that this build can create the app's
|
||||
// link (a dev build cannot: that is `npm run link` in apps/cli).
|
||||
// link (a dev build cannot: that is `npm run symlink:create`).
|
||||
export type CliStatus = {
|
||||
installed: boolean;
|
||||
path: string | null;
|
||||
@ -164,7 +146,7 @@ export type CliStatus = {
|
||||
available: boolean;
|
||||
};
|
||||
|
||||
// Outcome of linking the bundled diffusion CLI into PATH. "cancelled" means the
|
||||
// Outcome of linking the bundled dapi CLI into PATH. "cancelled" means the
|
||||
// user dismissed the macOS admin prompt — not an error, not installed.
|
||||
export type CliInstallResult =
|
||||
| { status: "installed" }
|
||||
@ -191,11 +173,6 @@ export type MainRequestMap = {
|
||||
request: { url: string };
|
||||
response: void;
|
||||
};
|
||||
// Where main sends events and as whom: on launch and every auth change.
|
||||
[MAIN_CHANNELS.ANALYTICS_CONFIGURE]: {
|
||||
request: { apiUrl: string; token: string | null };
|
||||
response: void;
|
||||
};
|
||||
[MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK]: {
|
||||
request: void;
|
||||
response: string | null;
|
||||
@ -205,11 +182,7 @@ export type MainRequestMap = {
|
||||
response: string | null;
|
||||
};
|
||||
[MAIN_CHANNELS.WINDOW_IS_FULLSCREEN]: { request: void; response: boolean };
|
||||
[MAIN_CHANNELS.WINDOW_SET_COLOR_MODE]: { request: { mode: "light" | "dark" }; response: void };
|
||||
[MAIN_CHANNELS.WINDOW_CAPTURE]: { request: void; response: ScreenshotResult };
|
||||
[MAIN_CHANNELS.WINDOW_SET_BUSY]: { request: { busy: boolean }; response: void };
|
||||
[MAIN_CHANNELS.WINDOW_SHOW]: { request: void; response: void };
|
||||
[MAIN_CHANNELS.CLIPBOARD_PATHS]: { request: void; response: string[] };
|
||||
[MAIN_CHANNELS.FILE_TRANSFER]: {
|
||||
request: { selector: string; absolutePath: string };
|
||||
response: void;
|
||||
@ -235,20 +208,25 @@ export type MainRequestMap = {
|
||||
request: { path: string };
|
||||
response: void;
|
||||
};
|
||||
// The code editors installed here that a folder can be opened in.
|
||||
[MAIN_CHANNELS.APP_EDITORS_LIST]: {
|
||||
request: void;
|
||||
response: EditorInfo[];
|
||||
};
|
||||
[MAIN_CHANNELS.APP_OPEN_IN_EDITOR]: {
|
||||
request: { id: EditorId; dir: string };
|
||||
response: void;
|
||||
};
|
||||
[MAIN_CHANNELS.LOGS_GET]: { request: void; response: LogEntry[] };
|
||||
[MAIN_CHANNELS.PROJECTS_PICK_ROOT]: {
|
||||
request: void;
|
||||
response: string | null;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_PICK_FOLDER]: {
|
||||
request: void;
|
||||
response: string | null;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT]: {
|
||||
request: void;
|
||||
response: string | null;
|
||||
};
|
||||
// Every project folder directly under `root`: what the app puts on its
|
||||
// list when `root` is chosen as the projects root.
|
||||
[MAIN_CHANNELS.PROJECTS_SCAN]: {
|
||||
request: { root: string };
|
||||
response: ProjectInfo[];
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_GET]: {
|
||||
request: { dir: string };
|
||||
response: ProjectInfo | null;
|
||||
@ -261,35 +239,11 @@ export type MainRequestMap = {
|
||||
request: { dir: string };
|
||||
response: ProjectInfo | null;
|
||||
};
|
||||
// The project `id` in a folder beside `dir`, which no longer holds it (a
|
||||
// folder renamed or moved in Finder); null when none does.
|
||||
[MAIN_CHANNELS.PROJECTS_FIND_MOVED]: {
|
||||
request: { dir: string; id: string };
|
||||
response: ProjectInfo | null;
|
||||
};
|
||||
// Asks what to do about a project whose folder can't be found.
|
||||
[MAIN_CHANNELS.PROJECTS_ASK_MISSING]: {
|
||||
request: { displayName: string; dir: string };
|
||||
response: MissingProjectChoice;
|
||||
};
|
||||
// A new project, as a draft called "Untitled" until it is saved.
|
||||
[MAIN_CHANNELS.PROJECTS_CREATE]: {
|
||||
request: void;
|
||||
response: ProjectInfo;
|
||||
};
|
||||
// Where to save a draft, or move a saved project; `name` fills the picker.
|
||||
[MAIN_CHANNELS.PROJECTS_PICK_SAVE]: {
|
||||
request: { dir: string; name: string; startIn: string | null; action: SaveAction };
|
||||
response: string | null;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_SAVE]: {
|
||||
request: { dir: string; target: string };
|
||||
response: ProjectInfo;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_MOVE]: {
|
||||
request: { dir: string; target: string };
|
||||
request: { root: string; displayName: string };
|
||||
response: ProjectInfo;
|
||||
};
|
||||
// Renames the project: `displayName` in the record, and the folder with it.
|
||||
[MAIN_CHANNELS.PROJECTS_RENAME]: {
|
||||
request: { dir: string; displayName: string };
|
||||
response: ProjectInfo;
|
||||
@ -358,7 +312,7 @@ export type MainRequestMap = {
|
||||
response: { url: string } | null;
|
||||
};
|
||||
// The app's MCP server in the agents' configs (see mcp-install.ts), and
|
||||
// the `diffusion` command on PATH (see cli-install.ts). The install/uninstall
|
||||
// the `dapi` command on PATH (see cli-install.ts). The install/uninstall
|
||||
// calls put the macOS admin prompt on screen.
|
||||
[MAIN_CHANNELS.MCP_STATUS]: { request: void; response: McpStatus };
|
||||
[MAIN_CHANNELS.MCP_APPLY]: { request: McpApplyRequest; response: McpApplyResult };
|
||||
|
||||
@ -8,37 +8,30 @@ import { existsSync } from "node:fs";
|
||||
import { mkdir, open, rename, unlink } from "node:fs/promises";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FileHandle } from "node:fs/promises";
|
||||
import type { IUpdateInfo } from "update-electron-app";
|
||||
import { makeUserNotifier, updateElectronApp } from "update-electron-app";
|
||||
import { updateElectronApp } from "update-electron-app";
|
||||
import { tempPathFor } from "./atomic";
|
||||
import { DapiServer } from "./dapi/server";
|
||||
import { agentChatEndpoint, configureAgentChat, deleteProjectChats, stopAgentChat } from "./agent-chat";
|
||||
import { cliStatus, installCli, refreshCliShim, uninstallCli } from "./cli-install";
|
||||
import { agentChatEndpoint, deleteProjectChats, startAgentChat, stopAgentChat } from "./agent-chat";
|
||||
import { cliStatus, installCli, uninstallCli } from "./cli-install";
|
||||
import { applyMcp, healMcpRegistrations, mcpStatus } from "./mcp-install";
|
||||
import { configureAnalytics, countCanvasEdits, startAnalytics, track } from "./analytics";
|
||||
import { enableHeadless } from "./headless";
|
||||
import { trackInstall } from "./analytics";
|
||||
import { setupAppMenu } from "./menu";
|
||||
import { clipboardPaths } from "./clipboard";
|
||||
import { installedEditors, openInEditor } from "./editors";
|
||||
import { AppTray } from "./tray";
|
||||
import { WindowHost } from "./window-host";
|
||||
import { handleSquirrelEvent } from "./squirrel";
|
||||
import { mainBridge } from "./main-manager";
|
||||
import { MAIN_CHANNELS } from "./main-channels";
|
||||
import {
|
||||
compileProject,
|
||||
createProject,
|
||||
defaultRoot,
|
||||
deleteProject,
|
||||
duplicateProject,
|
||||
getProject,
|
||||
askAboutMissingProject,
|
||||
findMovedProject,
|
||||
initProject,
|
||||
pickFolder,
|
||||
pickSaveLocation,
|
||||
pickRoot,
|
||||
renameProject,
|
||||
resolveProject,
|
||||
saveProject,
|
||||
moveProject,
|
||||
scanProjects,
|
||||
unwatchAll,
|
||||
listEntries,
|
||||
realPathEntry,
|
||||
@ -58,24 +51,9 @@ import type { DeepLinkChannel } from "./main-channels";
|
||||
import type { LogEntry } from "@diffusionstudio/dapi";
|
||||
|
||||
const DEV_URL = "http://localhost:5173";
|
||||
const WINDOW_IDLE_MS = 10 * 60 * 1000;
|
||||
const AUTH_PROTOCOL = "diffusion";
|
||||
const MACOS_CORNER_RADIUS = 18;
|
||||
const MACOS_BACKDROP = { blur: 80, red: 0.07, green: 0.07, blue: 0.07, alpha: 0.9 };
|
||||
// Window Controls Overlay on Windows: as tall as the renderer's `h-10` drag
|
||||
// strip, coloured like the sidebar it sits on (`--sidebar`), with symbols in
|
||||
// `--muted-foreground` like the other title bar icons. The dark value is that
|
||||
// token flattened onto the sidebar, since the overlay takes opaque colours.
|
||||
const WINDOWS_OVERLAY_HEIGHT = 40;
|
||||
const WINDOWS_OVERLAY_COLORS = {
|
||||
dark: { color: "#121212", symbolColor: "#a1a1a1" },
|
||||
light: { color: "#f7f7f7", symbolColor: "#737373" },
|
||||
};
|
||||
|
||||
// A Squirrel.Windows install/update/uninstall launch: housekeeping only, the
|
||||
// app quits on its own. Decided first so nothing below starts a service or
|
||||
// checks for updates on a launch that is about to end.
|
||||
const squirrelLaunch = handleSquirrelEvent();
|
||||
|
||||
app.setName("Diffusion Studio");
|
||||
app.commandLine.appendSwitch("enable-blink-features", "CanvasDrawElement");
|
||||
@ -107,55 +85,13 @@ function applyBackdrop() {
|
||||
setNativeBackdrop(mainWindow.getNativeWindowHandle(), blur, red, green, blue, alpha);
|
||||
}
|
||||
|
||||
function setColorMode(mode: "dark" | "light") {
|
||||
if (process.platform === "darwin" || !mainWindow || mainWindow.isDestroyed()) return;
|
||||
mainWindow.setTitleBarOverlay({ ...WINDOWS_OVERLAY_COLORS[mode], height: WINDOWS_OVERLAY_HEIGHT });
|
||||
}
|
||||
|
||||
// A downloaded update is offered while the user has the window out; one that
|
||||
// lands while the app runs in the background waits for the next show, since
|
||||
// the app rarely quits on its own to apply it.
|
||||
const notifyUser = makeUserNotifier();
|
||||
let pendingUpdate: IUpdateInfo | null = null;
|
||||
|
||||
function offerUpdate() {
|
||||
if (!pendingUpdate || !windows.visible()) return;
|
||||
const info = pendingUpdate;
|
||||
pendingUpdate = null;
|
||||
notifyUser(info);
|
||||
}
|
||||
|
||||
if (app.isPackaged && !squirrelLaunch) {
|
||||
updateElectronApp({
|
||||
repo: "diffusionstudio/editor",
|
||||
onNotifyUser: function (info) {
|
||||
pendingUpdate = info;
|
||||
offerUpdate();
|
||||
},
|
||||
});
|
||||
if (app.isPackaged && !process.argv.includes("--hidden")) {
|
||||
updateElectronApp({ repo: "diffusionstudio/editor" });
|
||||
}
|
||||
|
||||
const openWrites = new Map<string, { handle: FileHandle; path: string; temp: string; reserved: boolean }>();
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let lastProject: string | null = null;
|
||||
|
||||
const windows = new WindowHost({
|
||||
create: createWindow,
|
||||
idleMs: WINDOW_IDLE_MS,
|
||||
onChange: () => {
|
||||
tray.refresh();
|
||||
offerUpdate();
|
||||
},
|
||||
});
|
||||
|
||||
const tray = new AppTray({
|
||||
visible: () => windows.visible(),
|
||||
active: () => windows.active(),
|
||||
project: () => lastProject,
|
||||
show: () => void windows.show(),
|
||||
hide: () => windows.hide(),
|
||||
});
|
||||
|
||||
// Deep links that arrived before the renderer could take them, keyed by the
|
||||
// channel they belong to so auth and checkout never drain each other's link.
|
||||
@ -176,21 +112,13 @@ function docsDir(): string | null {
|
||||
return existsSync(dir) ? dir : null;
|
||||
}
|
||||
|
||||
// The MCP server agents and the diffusion CLI talk to. Started once the app is
|
||||
// ready; renderer tools create the window when there is none.
|
||||
// The MCP server agents and the dapi CLI talk to. Started once the app is
|
||||
// ready; the first connection switches the app into headless mode.
|
||||
const dapi = new DapiServer({
|
||||
version: app.getVersion(),
|
||||
logs: () => logBuffer,
|
||||
docsDir: docsDir(),
|
||||
window: {
|
||||
visible: () => windows.visible(),
|
||||
show: () => windows.show(),
|
||||
hide: () => windows.hide(),
|
||||
acquire: () => windows.acquire(),
|
||||
hold: () => windows.hold(),
|
||||
lastProject: () => lastProject,
|
||||
},
|
||||
onToolCall: (props) => track("tool_called", props),
|
||||
onFirstConnection: enableHeadless,
|
||||
});
|
||||
|
||||
function pushLog(level: LogEntry["level"], message: string, source: string) {
|
||||
@ -272,38 +200,20 @@ async function setFileInputFiles(selector: string, absolutePath: string) {
|
||||
});
|
||||
}
|
||||
|
||||
// The main window, not shown: WindowHost decides when it is.
|
||||
function createWindow(): BrowserWindow {
|
||||
|
||||
const options: Electron.BrowserWindowConstructorOptions = {
|
||||
function createWindow(show = true) {
|
||||
mainWindow = new BrowserWindow({
|
||||
show: false,
|
||||
width: 1200,
|
||||
height: 800,
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 14, y: 14 },
|
||||
...(process.platform === "darwin"
|
||||
? { vibrancy: "sidebar" as const, backgroundColor: "#00000000" }
|
||||
: { backgroundColor: "#1c1c1c" }),
|
||||
webPreferences: {
|
||||
preload: join(app.getAppPath(), "dist", "preload.js"),
|
||||
backgroundThrottling: false,
|
||||
},
|
||||
}
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
options.titleBarStyle = "hiddenInset" as const;
|
||||
options.trafficLightPosition = { x: 14, y: 14 };
|
||||
options.vibrancy = "sidebar" as const;
|
||||
options.backgroundColor = "#00000000";
|
||||
}
|
||||
|
||||
if (process.platform === "win32") {
|
||||
options.titleBarStyle = "hidden" as const;
|
||||
options.titleBarOverlay = { ...WINDOWS_OVERLAY_COLORS.dark, height: WINDOWS_OVERLAY_HEIGHT };
|
||||
options.autoHideMenuBar = true;
|
||||
options.backgroundColor = WINDOWS_OVERLAY_COLORS.dark.color;
|
||||
|
||||
if (!app.isPackaged) {
|
||||
options.icon = join(app.getAppPath(), "assets", "icon-dev.png");
|
||||
}
|
||||
}
|
||||
|
||||
mainWindow = new BrowserWindow(options);
|
||||
});
|
||||
|
||||
captureConsole(mainWindow);
|
||||
|
||||
@ -313,6 +223,10 @@ function createWindow(): BrowserWindow {
|
||||
mainWindow.once("ready-to-show", () => {
|
||||
applyCornerRadius(MACOS_CORNER_RADIUS);
|
||||
applyBackdrop();
|
||||
|
||||
if (show) {
|
||||
mainWindow?.show();
|
||||
}
|
||||
});
|
||||
|
||||
mainWindow.on("show", () => {
|
||||
@ -330,7 +244,6 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
mainWindow.on("closed", () => {
|
||||
mainWindow = null;
|
||||
unwatchAll();
|
||||
});
|
||||
|
||||
if (!app.isPackaged) {
|
||||
@ -338,8 +251,6 @@ function createWindow(): BrowserWindow {
|
||||
} else {
|
||||
mainWindow.loadFile(join(app.getAppPath(), "web", "index.html"));
|
||||
}
|
||||
|
||||
return mainWindow;
|
||||
}
|
||||
|
||||
if (process.defaultApp && process.argv.length >= 2) {
|
||||
@ -350,34 +261,29 @@ if (process.defaultApp && process.argv.length >= 2) {
|
||||
app.setAsDefaultProtocolClient(AUTH_PROTOCOL);
|
||||
}
|
||||
|
||||
if (squirrelLaunch) {
|
||||
// Update.exe is at work; handleSquirrelEvent quits the app when it is done.
|
||||
} else if (app.requestSingleInstanceLock()) {
|
||||
if (isHiddenLaunch(process.argv)) {
|
||||
app.dock?.hide();
|
||||
}
|
||||
|
||||
if (app.requestSingleInstanceLock()) {
|
||||
app.on("second-instance", (_event, argv) => {
|
||||
const url = findProtocolUrl(argv);
|
||||
if (url) {
|
||||
deliverDeepLink(url);
|
||||
}
|
||||
if (!isHiddenLaunch(argv)) {
|
||||
windows.show();
|
||||
if (url) deliverDeepLink(url);
|
||||
|
||||
const hidden = isHiddenLaunch(argv);
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
if (hidden) return;
|
||||
if (mainWindow.isMinimized()) mainWindow.restore();
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
} else {
|
||||
createWindow(!hidden);
|
||||
}
|
||||
});
|
||||
|
||||
app.on("open-url", (event, url) => {
|
||||
event.preventDefault();
|
||||
deliverDeepLink(url);
|
||||
windows.show();
|
||||
});
|
||||
|
||||
mainBridge.handle(MAIN_CHANNELS.APP_OPEN_EXTERNAL, ({ url }) => shell.openExternal(url));
|
||||
mainBridge.handle(MAIN_CHANNELS.APP_SHOW_IN_FOLDER, ({ path }) => shell.showItemInFolder(path));
|
||||
mainBridge.handle(MAIN_CHANNELS.APP_EDITORS_LIST, () => installedEditors());
|
||||
mainBridge.handle(MAIN_CHANNELS.APP_OPEN_IN_EDITOR, ({ id, dir }) => openInEditor(id, dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.ANALYTICS_CONFIGURE, (config) => configureAnalytics(config));
|
||||
mainBridge.handle(MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK, () =>
|
||||
takePendingDeepLink(MAIN_CHANNELS.AUTH_CALLBACK),
|
||||
);
|
||||
@ -385,9 +291,6 @@ if (squirrelLaunch) {
|
||||
takePendingDeepLink(MAIN_CHANNELS.CHECKOUT_CALLBACK),
|
||||
);
|
||||
mainBridge.handle(MAIN_CHANNELS.WINDOW_IS_FULLSCREEN, () => mainWindow?.isFullScreen() ?? false);
|
||||
mainBridge.handle(MAIN_CHANNELS.WINDOW_SET_COLOR_MODE, ({ mode }) => setColorMode(mode));
|
||||
mainBridge.handle(MAIN_CHANNELS.WINDOW_SET_BUSY, ({ busy }) => windows.setBusy(busy));
|
||||
mainBridge.handle(MAIN_CHANNELS.WINDOW_SHOW, () => windows.show());
|
||||
mainBridge.handle(MAIN_CHANNELS.WINDOW_CAPTURE, async () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) throw new Error("No main window");
|
||||
const image = await mainWindow.webContents.capturePage(undefined, { stayHidden: true });
|
||||
@ -396,7 +299,6 @@ if (squirrelLaunch) {
|
||||
// A plain Uint8Array over the PNG, so the renderer sees bytes and not a Buffer.
|
||||
return { png: new Uint8Array(png.buffer, png.byteOffset, png.byteLength), width, height };
|
||||
});
|
||||
mainBridge.handle(MAIN_CHANNELS.CLIPBOARD_PATHS, () => clipboardPaths());
|
||||
mainBridge.handle(MAIN_CHANNELS.LOGS_GET, () => logBuffer);
|
||||
mainBridge.handle(MAIN_CHANNELS.AGENT_CHAT_ENDPOINT, () => agentChatEndpoint());
|
||||
mainBridge.handle(MAIN_CHANNELS.MCP_STATUS, () => mcpStatus());
|
||||
@ -404,40 +306,25 @@ if (squirrelLaunch) {
|
||||
mainBridge.handle(MAIN_CHANNELS.CLI_STATUS, () => cliStatus());
|
||||
mainBridge.handle(MAIN_CHANNELS.CLI_INSTALL, () => installCli());
|
||||
mainBridge.handle(MAIN_CHANNELS.CLI_UNINSTALL, () => uninstallCli());
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_FOLDER, () => pickFolder(mainWindow));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT, () => defaultRoot(mainWindow));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_SCAN, ({ root }) => scanProjects(root));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_GET, ({ dir }) => getProject(dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_INIT, ({ dir }) => initProject(mainWindow, dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_RESOLVE, ({ dir }) => resolveProject(dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_FIND_MOVED, ({ dir, id }) => findMovedProject(dir, id));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_ASK_MISSING, ({ displayName, dir }) =>
|
||||
askAboutMissingProject(mainWindow, displayName, dir),
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, displayName }) =>
|
||||
createProject(root, displayName),
|
||||
);
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, () => createProject());
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_SAVE, ({ dir, name, startIn, action }) =>
|
||||
pickSaveLocation(mainWindow, dir, name, startIn, action),
|
||||
);
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_SAVE, ({ dir, target }) => saveProject(dir, target));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_MOVE, ({ dir, target }) => moveProject(dir, target));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_RENAME, ({ dir, displayName }) => renameProject(dir, displayName));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_DUPLICATE, ({ dir }) => duplicateProject(dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_DELETE, ({ dir }) => deleteProject(dir).then(deleteProjectChats));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_COMPILE, ({ dir }) => compileProject(dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_WRITE, ({ dir, edits }) => {
|
||||
countCanvasEdits(edits.map((edit) => edit.kind));
|
||||
return writeProject(dir, edits);
|
||||
});
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) => {
|
||||
lastProject = dir;
|
||||
tray.refresh();
|
||||
watchProject(BrowserWindow.fromWebContents(event.sender), dir);
|
||||
});
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_UNWATCH, ({ dir }) => {
|
||||
if (lastProject === dir) {
|
||||
lastProject = null;
|
||||
tray.refresh();
|
||||
}
|
||||
unwatchProject(dir);
|
||||
});
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_WRITE, ({ dir, edits }) => writeProject(dir, edits));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) =>
|
||||
watchProject(BrowserWindow.fromWebContents(event.sender), dir),
|
||||
);
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_UNWATCH, ({ dir }) => unwatchProject(dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_MANIFEST_READ, ({ dir }) => readManifest(dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_MANIFEST_WRITE, ({ dir, manifest }) => writeManifest(dir, manifest));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_CONFIG_READ, ({ dir }) => readConfig(dir));
|
||||
@ -527,38 +414,44 @@ if (squirrelLaunch) {
|
||||
if (url) deliverDeepLink(url);
|
||||
|
||||
dapi.start();
|
||||
// The chat's sessions get the MCP server by URL.
|
||||
// The chat's sessions get the MCP server by URL; `?client=chat` keeps the
|
||||
// app from switching into remote-controlled mode for them (see dapi/http).
|
||||
dapi.mcpUrl().then((url) =>
|
||||
configureAgentChat({
|
||||
startAgentChat({
|
||||
dataDir: join(app.getPath("userData"), "agent-chat"),
|
||||
mcpUrl: url,
|
||||
mcpUrl: url ? `${url}?client=chat` : null,
|
||||
version: app.getVersion(),
|
||||
}),
|
||||
);
|
||||
refreshCliShim();
|
||||
healMcpRegistrations();
|
||||
startAnalytics(windows);
|
||||
tray.start();
|
||||
|
||||
// Opened by a person (Finder, Dock, Start menu): show the editor
|
||||
if (!isHiddenLaunch(process.argv)) {
|
||||
windows.show();
|
||||
}
|
||||
trackInstall();
|
||||
createWindow(!isHiddenLaunch(process.argv));
|
||||
});
|
||||
|
||||
app.on("before-quit", () => {
|
||||
unwatchAll();
|
||||
stopAgentChat();
|
||||
dapi.stop();
|
||||
tray.destroy();
|
||||
});
|
||||
|
||||
// No window is no reason to quit: the app keeps serving agents from the
|
||||
// tray, and the window is destroyed whenever it idles out. Only Quit ends it.
|
||||
app.on("window-all-closed", () => { });
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
|
||||
// The Dock icon, or launching the app again while it runs.
|
||||
app.on("activate", () => windows.show());
|
||||
app.on("activate", () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||
createWindow();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mainWindow.isMinimized()) {
|
||||
mainWindow.restore();
|
||||
}
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
});
|
||||
} else {
|
||||
app.quit();
|
||||
}
|
||||
|
||||
@ -3,16 +3,7 @@
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
AGENT_TARGETS,
|
||||
agentTarget,
|
||||
needsBinary,
|
||||
readServer,
|
||||
removeServer,
|
||||
runsOurProxy,
|
||||
sameCommand,
|
||||
upsertServer,
|
||||
} from "./mcp-config";
|
||||
import { AGENT_TARGETS, agentTarget, needsBinary, readServer, removeServer, upsertServer } from "./mcp-config";
|
||||
|
||||
const spec = {
|
||||
url: "http://127.0.0.1:3274/mcp",
|
||||
@ -29,7 +20,6 @@ describe("per-agent entries", () => {
|
||||
expect(agentTarget("antigravity").entry(spec)).toEqual({ serverUrl: spec.url });
|
||||
expect(agentTarget("gemini-cli").entry(spec)).toEqual({ httpUrl: spec.url });
|
||||
expect(agentTarget("windsurf").entry(spec)).toEqual({ serverUrl: spec.url });
|
||||
expect(agentTarget("opencode").entry(spec)).toEqual({ type: "remote", enabled: true, url: spec.url });
|
||||
});
|
||||
|
||||
it("gives Claude Desktop the stdio proxy, and nobody else", () => {
|
||||
@ -57,12 +47,6 @@ describe("json configs", () => {
|
||||
expect(readServer(text, "mcpServers")).toBeNull();
|
||||
});
|
||||
|
||||
it("uses OpenCode's root key and keeps the boolean flag", () => {
|
||||
const text = upsertServer(null, "mcp", { type: "remote", enabled: true, url: spec.url });
|
||||
expect(JSON.parse(text)).toEqual({ mcp: { diffusion: { type: "remote", enabled: true, url: spec.url } } });
|
||||
expect(readServer(text, "mcp")).toEqual({ url: spec.url });
|
||||
});
|
||||
|
||||
it("keeps other servers and unrelated keys", () => {
|
||||
const before = JSON.stringify({
|
||||
numStartups: 12,
|
||||
@ -78,7 +62,7 @@ describe("json configs", () => {
|
||||
|
||||
it("replaces a stdio entry with a URL entry, and reads either", () => {
|
||||
const before = upsertServer(null, "mcpServers", { command: "/old/dapi", args: ["mcp"] });
|
||||
expect(readServer(before, "mcpServers")).toEqual({ command: "/old/dapi", args: ["mcp"] });
|
||||
expect(readServer(before, "mcpServers")).toEqual({ command: "/old/dapi" });
|
||||
const after = upsertServer(before, "mcpServers", { type: "http", url: spec.url });
|
||||
expect(readServer(after, "mcpServers")).toEqual({ url: spec.url });
|
||||
expect(JSON.parse(after).mcpServers.diffusion.command).toBeUndefined();
|
||||
@ -130,7 +114,7 @@ describe("toml configs (codex)", () => {
|
||||
|
||||
it("replaces our table in place and leaves the next one alone", () => {
|
||||
const before = '[mcp_servers.diffusion]\ncommand = "/old/dapi"\nargs = ["mcp"]\n\n[mcp_servers.other]\ncommand = "x"\n';
|
||||
expect(readServer(before, "toml")).toEqual({ command: "/old/dapi", args: ["mcp"] });
|
||||
expect(readServer(before, "toml")).toEqual({ command: "/old/dapi" });
|
||||
const after = upsertServer(before, "toml", { url: spec.url });
|
||||
expect(after).toBe('[mcp_servers.diffusion]\nurl = "http://127.0.0.1:3274/mcp"\n[mcp_servers.other]\ncommand = "x"\n');
|
||||
expect(readServer(after, "toml")).toEqual({ url: spec.url });
|
||||
@ -145,7 +129,7 @@ describe("toml configs (codex)", () => {
|
||||
const odd = { command: 'C:\\Apps\\"Diffusion"\\dapi', args: ["mcp"] };
|
||||
const text = upsertServer(null, "toml", odd);
|
||||
expect(text).toContain('command = "C:\\\\Apps\\\\\\"Diffusion\\"\\\\dapi"');
|
||||
expect(readServer(text, "toml")).toEqual({ command: odd.command, args: ["mcp"] });
|
||||
expect(readServer(text, "toml")).toEqual({ command: odd.command });
|
||||
});
|
||||
|
||||
it("reads nothing from a config without our table", () => {
|
||||
@ -168,36 +152,3 @@ describe("toml configs (codex)", () => {
|
||||
expect(removeServer(upsertServer(null, "toml", { url: spec.url }), "toml")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stdio entries across platforms", () => {
|
||||
const shim = "C:\\Users\\me\\AppData\\Local\\DiffusionStudio\\bin\\dapi.cmd";
|
||||
const windows = { url: spec.url, command: "cmd", args: ["/c", shim, "mcp"] };
|
||||
|
||||
it("keeps desktop apps' configs under appData and the dotfile agents under home", () => {
|
||||
expect(agentTarget("claude-desktop").config).toEqual({ root: "appData", path: "Claude/claude_desktop_config.json" });
|
||||
expect(agentTarget("vscode").config).toEqual({ root: "appData", path: "Code/User/mcp.json" });
|
||||
expect(AGENT_TARGETS.filter((t) => t.config.root === "appData").map((t) => t.id)).toEqual(["claude-desktop", "vscode"]);
|
||||
});
|
||||
|
||||
it("round-trips the Windows shape, where the shim rides in args", () => {
|
||||
const entry = agentTarget("claude-desktop").entry(windows);
|
||||
expect(entry).toEqual({ command: "cmd", args: ["/c", shim, "mcp"] });
|
||||
const registered = readServer(upsertServer(null, "mcpServers", entry), "mcpServers");
|
||||
expect(registered).toEqual({ command: "cmd", args: ["/c", shim, "mcp"] });
|
||||
expect(sameCommand(registered!, entry)).toBe(true);
|
||||
});
|
||||
|
||||
it("recognises our proxy by its path, as the command or as an argument", () => {
|
||||
expect(runsOurProxy({ command: spec.command, args: ["mcp"] })).toBe(true);
|
||||
expect(runsOurProxy({ command: "/private/var/folders/x/AppTranslocation/y/d/cli/bin/dapi" })).toBe(true);
|
||||
expect(runsOurProxy({ command: "cmd", args: ["/c", shim, "mcp"] })).toBe(true);
|
||||
expect(runsOurProxy({ command: "cmd", args: ["/c", "C:\\tools\\other.cmd"] })).toBe(false);
|
||||
expect(runsOurProxy({ command: "/opt/homebrew/bin/dapi", args: ["mcp"] })).toBe(false);
|
||||
});
|
||||
|
||||
it("sees a moved shim as a different command", () => {
|
||||
const moved = { command: "cmd", args: ["/c", shim.replace("me", "you"), "mcp"] };
|
||||
expect(sameCommand(moved, agentTarget("claude-desktop").entry(windows))).toBe(false);
|
||||
expect(sameCommand({ command: spec.command, args: ["mcp"] }, agentTarget("claude-desktop").entry(spec))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@ -9,22 +9,20 @@
|
||||
/**
|
||||
* The two ways to reach the app. Agents that speak Streamable HTTP get the
|
||||
* URL, which is the same on every machine; the rest get the bundled `dapi`
|
||||
* binary in stdio proxy mode. On Windows that binary is a `.cmd`, which
|
||||
* nothing can spawn without a shell, so the command is `cmd` and the shim's
|
||||
* path rides in `args`.
|
||||
* binary in stdio proxy mode.
|
||||
*/
|
||||
export type McpServerSpec = { url: string; command: string; args: string[] };
|
||||
|
||||
/**
|
||||
* The key our entry lives under in every agent's server map, and so the
|
||||
* namespace an agent shows us under: `mcp__diffusion__<tool>` and
|
||||
* `/diffusion:<prompt>`. The same word as our URL scheme and the CLI's
|
||||
* primary name (`dapi` still works there too, as an alias).
|
||||
* `/diffusion:<prompt>`. The same word as our URL scheme, and not `dapi`,
|
||||
* which is the CLI.
|
||||
*/
|
||||
export const SERVER_NAME = "diffusion";
|
||||
|
||||
/** One agent's config entry: what its file format spells a server as. */
|
||||
export type ServerEntry = Record<string, string | string[] | boolean>;
|
||||
export type ServerEntry = Record<string, string | string[]>;
|
||||
|
||||
/** The stable id an agent is addressed by over IPC and in the UI. */
|
||||
export type AgentId =
|
||||
@ -35,28 +33,19 @@ export type AgentId =
|
||||
| "codex"
|
||||
| "antigravity"
|
||||
| "gemini-cli"
|
||||
| "windsurf"
|
||||
| "opencode";
|
||||
| "windsurf";
|
||||
|
||||
/** How a config file spells its server map: JSON under `mcpServers` (or VS Code's `servers`, or OpenCode's `mcp`), or Codex's TOML tables. */
|
||||
export type ConfigFormat = "mcpServers" | "servers" | "mcp" | "toml";
|
||||
|
||||
/**
|
||||
* A path under one of the two per-user roots. `appData` is where desktop apps
|
||||
* keep their files (Electron's `appData`: ~/Library/Application Support on
|
||||
* macOS, %APPDATA% on Windows), which keeps this table the same on every
|
||||
* platform; `mcp-install.ts` knows where the roots are.
|
||||
*/
|
||||
export type AgentPath = { root: "home" | "appData"; path: string };
|
||||
/** How a config file spells its server map: JSON under `mcpServers` (or VS Code's `servers`), or Codex's TOML tables. */
|
||||
export type ConfigFormat = "mcpServers" | "servers" | "toml";
|
||||
|
||||
export type AgentTarget = {
|
||||
id: AgentId;
|
||||
/** Human name, for the UI. */
|
||||
label: string;
|
||||
/** Path whose presence means the agent is set up on this machine. */
|
||||
marker: AgentPath;
|
||||
/** Path of the config file our entry goes into. */
|
||||
config: AgentPath;
|
||||
/** Home-relative path whose presence means the agent is set up on this machine. */
|
||||
marker: string;
|
||||
/** Home-relative path of the config file our entry goes into. */
|
||||
config: string;
|
||||
format: ConfigFormat;
|
||||
/** The entry for this agent: which transport it gets, under the keys its format uses. */
|
||||
entry(spec: McpServerSpec): ServerEntry;
|
||||
@ -65,8 +54,8 @@ export type AgentTarget = {
|
||||
const http = (key: string, extra: ServerEntry = {}) => (spec: McpServerSpec): ServerEntry => ({ ...extra, [key]: spec.url });
|
||||
const stdio = (spec: McpServerSpec): ServerEntry => ({ command: spec.command, args: [...spec.args] });
|
||||
|
||||
const home = (path: string): AgentPath => ({ root: "home", path });
|
||||
const appData = (path: string): AgentPath => ({ root: "appData", path });
|
||||
/** Where macOS apps keep their per-user files; agents that are desktop apps put their config there. */
|
||||
const APP_SUPPORT = "Library/Application Support";
|
||||
|
||||
// Agents whose MCP config we know how to write, in the order the UI lists
|
||||
// them. Claude Code's user scope is the top-level `mcpServers` of
|
||||
@ -76,29 +65,28 @@ const appData = (path: string): AgentPath => ({ root: "appData", path });
|
||||
// `serverUrl`. Claude Desktop's file takes stdio commands only, so it gets
|
||||
// the proxy.
|
||||
export const AGENT_TARGETS: readonly AgentTarget[] = [
|
||||
{ id: "claude-code", label: "Claude Code", marker: home(".claude"), config: home(".claude.json"), format: "mcpServers", entry: http("url", { type: "http" }) },
|
||||
{ id: "claude-code", label: "Claude Code", marker: ".claude", config: ".claude.json", format: "mcpServers", entry: http("url", { type: "http" }) },
|
||||
{
|
||||
id: "claude-desktop",
|
||||
label: "Claude Desktop",
|
||||
marker: appData("Claude"),
|
||||
config: appData("Claude/claude_desktop_config.json"),
|
||||
marker: `${APP_SUPPORT}/Claude`,
|
||||
config: `${APP_SUPPORT}/Claude/claude_desktop_config.json`,
|
||||
format: "mcpServers",
|
||||
entry: stdio,
|
||||
},
|
||||
{ id: "cursor", label: "Cursor", marker: home(".cursor"), config: home(".cursor/mcp.json"), format: "mcpServers", entry: http("url") },
|
||||
{ id: "cursor", label: "Cursor", marker: ".cursor", config: ".cursor/mcp.json", format: "mcpServers", entry: http("url") },
|
||||
{
|
||||
id: "vscode",
|
||||
label: "VS Code (Copilot)",
|
||||
marker: appData("Code"),
|
||||
config: appData("Code/User/mcp.json"),
|
||||
marker: `${APP_SUPPORT}/Code`,
|
||||
config: `${APP_SUPPORT}/Code/User/mcp.json`,
|
||||
format: "servers",
|
||||
entry: http("url", { type: "http" }),
|
||||
},
|
||||
{ id: "codex", label: "Codex", marker: home(".codex"), config: home(".codex/config.toml"), format: "toml", entry: http("url") },
|
||||
{ id: "antigravity", label: "Antigravity", marker: home(".gemini/antigravity"), config: home(".gemini/config/mcp_config.json"), format: "mcpServers", entry: http("serverUrl") },
|
||||
{ id: "gemini-cli", label: "Gemini CLI", marker: home(".gemini"), config: home(".gemini/settings.json"), format: "mcpServers", entry: http("httpUrl") },
|
||||
{ id: "windsurf", label: "Devin (Windsurf)", marker: home(".codeium/windsurf"), config: home(".codeium/windsurf/mcp_config.json"), format: "mcpServers", entry: http("serverUrl") },
|
||||
{ id: "opencode", label: "OpenCode", marker: home(".config/opencode"), config: home(".config/opencode/opencode.json"), format: "mcp", entry: http("url", { type: "remote", enabled: true }) },
|
||||
{ id: "codex", label: "Codex", marker: ".codex", config: ".codex/config.toml", format: "toml", entry: http("url") },
|
||||
{ id: "antigravity", label: "Antigravity", marker: ".gemini/antigravity", config: ".gemini/config/mcp_config.json", format: "mcpServers", entry: http("serverUrl") },
|
||||
{ id: "gemini-cli", label: "Gemini CLI", marker: ".gemini", config: ".gemini/settings.json", format: "mcpServers", entry: http("httpUrl") },
|
||||
{ id: "windsurf", label: "Devin (Windsurf)", marker: ".codeium/windsurf", config: ".codeium/windsurf/mcp_config.json", format: "mcpServers", entry: http("serverUrl") },
|
||||
];
|
||||
|
||||
export function agentTarget(id: AgentId): AgentTarget {
|
||||
@ -133,7 +121,7 @@ export function removeServer(text: string | null, format: ConfigFormat): string
|
||||
}
|
||||
|
||||
/** Where our entry currently points, whatever keys the agent spells it with; null when there is none. */
|
||||
export type Registered = { url?: string; command?: string; args?: string[] };
|
||||
export type Registered = { url?: string; command?: string };
|
||||
|
||||
export function readServer(text: string | null, format: ConfigFormat): Registered | null {
|
||||
if (text === null) return null;
|
||||
@ -142,40 +130,12 @@ export function readServer(text: string | null, format: ConfigFormat): Registere
|
||||
const url = entry.url ?? entry.httpUrl ?? entry.serverUrl;
|
||||
const command = entry.command;
|
||||
if (typeof url !== "string" && typeof command !== "string") return null;
|
||||
const args = Array.isArray(entry.args) ? entry.args.filter((arg): arg is string => typeof arg === "string") : null;
|
||||
return {
|
||||
...(typeof url === "string" ? { url } : {}),
|
||||
...(typeof command === "string" ? { command } : {}),
|
||||
...(typeof command === "string" && args ? { args } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// What a path to our proxy has in it: the app's name inside a macOS bundle
|
||||
// (or the translocated mount a quarantined bundle ran from), the Squirrel
|
||||
// package id in the Windows shim folder.
|
||||
const OUR_PATHS = ["Diffusion Studio", "/AppTranslocation/", "\\DiffusionStudio\\"];
|
||||
|
||||
/**
|
||||
* Whether a stdio entry runs our proxy — from wherever the app was when the
|
||||
* entry was written — rather than something the user put under our name by
|
||||
* hand. The path is the command itself, or on Windows an argument to `cmd`.
|
||||
*/
|
||||
export function runsOurProxy(registered: Registered): boolean {
|
||||
return [registered.command ?? "", ...(registered.args ?? [])].some((part) =>
|
||||
OUR_PATHS.some((marker) => part.includes(marker)),
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether a stdio entry already is what `entry` would write. */
|
||||
export function sameCommand(registered: Registered, entry: ServerEntry): boolean {
|
||||
const args = Array.isArray(entry.args) ? entry.args : [];
|
||||
return (
|
||||
registered.command === entry.command &&
|
||||
(registered.args ?? []).length === args.length &&
|
||||
(registered.args ?? []).every((arg, index) => arg === args[index])
|
||||
);
|
||||
}
|
||||
|
||||
// --- JSON ------------------------------------------------------------------
|
||||
|
||||
type JsonFormat = Exclude<ConfigFormat, "toml">;
|
||||
@ -231,8 +191,7 @@ function tomlString(value: string): string {
|
||||
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
||||
}
|
||||
|
||||
function tomlValue(value: string | string[] | boolean): string {
|
||||
if (typeof value === "boolean") return String(value);
|
||||
function tomlValue(value: string | string[]): string {
|
||||
return Array.isArray(value) ? `[${value.map(tomlString).join(", ")}]` : tomlString(value);
|
||||
}
|
||||
|
||||
|
||||
@ -6,92 +6,57 @@
|
||||
// at a time as the settings page asks: the fixed loopback URL for agents
|
||||
// that speak HTTP, the bundled `dapi mcp` proxy for the rest. No PATH
|
||||
// symlink and no admin prompt — that is `cli-install.ts`, for people who
|
||||
// type `diffusion` (or its `dapi` alias).
|
||||
// type `dapi`.
|
||||
|
||||
import { app } from "electron";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { MCP_URL } from "@diffusionstudio/dapi";
|
||||
import { shimPath } from "./cli-windows";
|
||||
import {
|
||||
AGENT_TARGETS,
|
||||
agentTarget,
|
||||
needsBinary,
|
||||
readServer,
|
||||
removeServer,
|
||||
runsOurProxy,
|
||||
sameCommand,
|
||||
upsertServer,
|
||||
} from "./mcp-config";
|
||||
import { AGENT_TARGETS, agentTarget, needsBinary, readServer, removeServer, upsertServer } from "./mcp-config";
|
||||
|
||||
import type { AgentPath, AgentTarget, McpServerSpec } from "./mcp-config";
|
||||
import type { AgentTarget, McpServerSpec } from "./mcp-config";
|
||||
import type { McpAgentStatus, McpApplyRequest, McpApplyResult, McpStatus } from "./main-channels";
|
||||
|
||||
// The dev workflow links the workspace build into Homebrew's bin
|
||||
// (`npm run link` in apps/cli); that is the binary a dev build registers.
|
||||
// (`symlink:create` in apps/cli); that is the binary a dev build registers.
|
||||
const DEV_BINARY = "/opt/homebrew/bin/dapi";
|
||||
|
||||
/**
|
||||
* The bundled `dapi` binary, or null when none is available (an unstaged dev
|
||||
* build). On Windows it is the shim outside the install folder, the one path
|
||||
* that survives an update; a packaged app writes it on every launch, so it
|
||||
* counts as there even in the moment before that write lands.
|
||||
*/
|
||||
/** The bundled `dapi` binary, or null when none is available (an unstaged dev build). */
|
||||
export function dapiBinary(): string | null {
|
||||
if (process.platform === "win32") {
|
||||
const shim = shimPath();
|
||||
return app.isPackaged || existsSync(shim) ? shim : null;
|
||||
}
|
||||
const command = app.isPackaged ? join(process.resourcesPath, "cli", "bin", "dapi") : DEV_BINARY;
|
||||
return existsSync(command) ? command : null;
|
||||
}
|
||||
|
||||
function spec(): McpServerSpec {
|
||||
const binary = dapiBinary();
|
||||
if (!binary) {
|
||||
return { url: MCP_URL, command: "", args: [] };
|
||||
}
|
||||
// A `.cmd` only runs through a shell, and the agents spawn without one.
|
||||
if (process.platform === "win32") {
|
||||
return { url: MCP_URL, command: "cmd", args: ["/c", binary, "mcp"] };
|
||||
}
|
||||
|
||||
return { url: MCP_URL, command: binary, args: ["mcp"] };
|
||||
return { url: MCP_URL, command: dapiBinary() ?? "", args: ["mcp"] };
|
||||
}
|
||||
|
||||
function resolvePath(location: AgentPath): string {
|
||||
if (location.root === "home") {
|
||||
return join(homedir(), location.path);
|
||||
}
|
||||
if (location.root === "appData") {
|
||||
return join(app.getPath("appData"), location.path);
|
||||
}
|
||||
|
||||
throw new Error(`Unknown agent path root: ${location.root}`);
|
||||
function configPath(target: AgentTarget): string {
|
||||
return join(homedir(), target.config);
|
||||
}
|
||||
|
||||
function readConfig(target: AgentTarget): string | null {
|
||||
const path = resolvePath(target.config);
|
||||
const path = configPath(target);
|
||||
return existsSync(path) ? readFileSync(path, "utf8") : null;
|
||||
}
|
||||
|
||||
function writeConfig(target: AgentTarget, text: string): void {
|
||||
const path = resolvePath(target.config);
|
||||
const path = configPath(target);
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
writeFileSync(path, text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Why this agent cannot be connected from this build, or null when it can.
|
||||
* Only the stdio agents have reasons: a build without the `diffusion` binary has
|
||||
* Only the stdio agents have reasons: a build without the `dapi` binary has
|
||||
* nothing for them to run, and a quarantined first launch runs from a
|
||||
* translocated read-only mount whose path won't survive the next launch —
|
||||
* registering it would dangle.
|
||||
*/
|
||||
function unavailableReason(target: AgentTarget, current: McpServerSpec): string | null {
|
||||
if (!needsBinary(target)) return null;
|
||||
if (current.command === "") return "Needs the diffusion command line tool, which this build does not include.";
|
||||
if (current.command === "") return "Needs the dapi command line tool, which this build does not include.";
|
||||
if (app.isPackaged && current.command.includes("/AppTranslocation/")) {
|
||||
return "Move Diffusion Studio to the Applications folder and relaunch it first.";
|
||||
}
|
||||
@ -103,9 +68,9 @@ function agentStatus(target: AgentTarget, current: McpServerSpec): McpAgentStatu
|
||||
return {
|
||||
id: target.id,
|
||||
label: target.label,
|
||||
detected: existsSync(resolvePath(target.marker)),
|
||||
detected: existsSync(join(homedir(), target.marker)),
|
||||
connected: registered !== null,
|
||||
config: resolvePath(target.config),
|
||||
config: configPath(target),
|
||||
unavailable: unavailableReason(target, current),
|
||||
};
|
||||
}
|
||||
@ -136,7 +101,7 @@ export function applyMcp(request: McpApplyRequest): McpApplyResult {
|
||||
writeConfig(target, upsertServer(readConfig(target), target.format, target.entry(current)));
|
||||
result.added.push(id);
|
||||
} catch (e) {
|
||||
result.failures.push({ id, error: `${target.config.path}: ${(e as Error).message}` });
|
||||
result.failures.push({ id, error: `${target.config}: ${(e as Error).message}` });
|
||||
}
|
||||
}
|
||||
|
||||
@ -147,7 +112,7 @@ export function applyMcp(request: McpApplyRequest): McpApplyResult {
|
||||
if (next !== null) writeConfig(target, next);
|
||||
result.removed.push(id);
|
||||
} catch (e) {
|
||||
result.failures.push({ id, error: `${target.config.path}: ${(e as Error).message}` });
|
||||
result.failures.push({ id, error: `${target.config}: ${(e as Error).message}` });
|
||||
}
|
||||
}
|
||||
|
||||
@ -169,10 +134,10 @@ export function healMcpRegistrations(): void {
|
||||
const text = readConfig(target);
|
||||
const registered = readServer(text, target.format);
|
||||
if (!registered?.command) continue;
|
||||
if (!runsOurProxy(registered)) continue;
|
||||
const ours = registered.command.includes("Diffusion Studio") || registered.command.includes("/AppTranslocation/");
|
||||
if (!ours) continue;
|
||||
const entry = target.entry(current);
|
||||
if (sameCommand(registered, entry)) continue;
|
||||
|
||||
if (registered.command === entry.command) continue;
|
||||
try {
|
||||
writeConfig(target, upsertServer(text, target.format, entry));
|
||||
} catch {
|
||||
|
||||
@ -6,13 +6,10 @@ import { app, Menu } from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
|
||||
export function setupAppMenu() {
|
||||
// The app submenu is a macOS convention. Elsewhere the same role menus sit
|
||||
// behind Alt (the window hides the bar) and exist for their accelerators:
|
||||
// reload, devtools, zoom, quit.
|
||||
const template: MenuItemConstructorOptions[] = []
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
if (process.platform === "darwin") {
|
||||
template.push({
|
||||
const template: MenuItemConstructorOptions[] = [
|
||||
{
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
@ -25,15 +22,12 @@ export function setupAppMenu() {
|
||||
{ type: "separator" },
|
||||
{ role: "quit" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
template.push(
|
||||
},
|
||||
{ role: "fileMenu" },
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
);
|
||||
];
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
}
|
||||
|
||||
@ -1,98 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// A new project is a draft: made without asking, in the app's own folder,
|
||||
// named after its id — until it is saved, which moves it where the user said
|
||||
// and names it after the folder they chose.
|
||||
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdir, mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
let userData = "";
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: { isPackaged: false, getPath: (name: string) => (name === "userData" ? userData : tmpdir()) },
|
||||
dialog: {},
|
||||
shell: {},
|
||||
ipcMain: { on: () => { } },
|
||||
}));
|
||||
|
||||
const { createProject, draftsRoot, duplicateProject, moveProject, readManifest, saveProject, writeManifest } =
|
||||
await import("./projects");
|
||||
|
||||
let root: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), "drafts-test-"));
|
||||
userData = join(root, "userData");
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("drafts", () => {
|
||||
it("creates a draft in the drafts folder, named after its id", async () => {
|
||||
const project = await createProject();
|
||||
expect(project.draft).toBe(true);
|
||||
expect(project.dir).toBe(join(draftsRoot(), project.id));
|
||||
expect(project.name).toBe(project.id);
|
||||
expect(project.displayName).toBe("Untitled");
|
||||
expect(project.entry).toBe("index.tsx");
|
||||
});
|
||||
|
||||
it("duplicates a draft as a draft with an id of its own", async () => {
|
||||
const source = await createProject();
|
||||
const copy = await duplicateProject(source.dir);
|
||||
expect(copy.draft).toBe(true);
|
||||
expect(copy.id).not.toBe(source.id);
|
||||
expect(copy.dir).toBe(join(draftsRoot(), copy.id));
|
||||
});
|
||||
|
||||
it("saves a draft by moving it and naming it after the folder", async () => {
|
||||
const draft = await createProject();
|
||||
const target = join(root, "Saved", "My Ad");
|
||||
|
||||
const saved = await saveProject(draft.dir, target);
|
||||
expect(saved).toMatchObject({ id: draft.id, dir: target, name: "My Ad", displayName: "My Ad", draft: false });
|
||||
expect(await readdir(draftsRoot())).toEqual([]);
|
||||
const pkg = JSON.parse(await readFile(join(target, "package.json"), "utf8"));
|
||||
expect(pkg.projectId).toBe(draft.id);
|
||||
});
|
||||
|
||||
it("lands a write asked for before the save in the saved folder", async () => {
|
||||
const draft = await createProject();
|
||||
const target = join(root, "My Ad");
|
||||
|
||||
const manifest = { version: 1, folders: [], assets: [{ id: "a" }] };
|
||||
const writing = writeManifest(draft.dir, manifest);
|
||||
await saveProject(draft.dir, target);
|
||||
await writing;
|
||||
expect(await readManifest(target)).toEqual(manifest);
|
||||
expect(await readdir(draftsRoot())).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses a folder that exists, and a project that is not a draft", async () => {
|
||||
const draft = await createProject();
|
||||
const taken = join(root, "taken");
|
||||
await mkdir(taken);
|
||||
await expect(saveProject(draft.dir, taken)).rejects.toThrow(/already exists/);
|
||||
|
||||
const saved = await saveProject(draft.dir, join(root, "saved"));
|
||||
await expect(saveProject(saved.dir, join(root, "again"))).rejects.toThrow(/saved already/);
|
||||
});
|
||||
|
||||
it("moves a saved project, keeping its name, and refuses to move a draft", async () => {
|
||||
const draft = await createProject();
|
||||
await expect(moveProject(draft.dir, join(root, "elsewhere"))).rejects.toThrow(/Save the draft/);
|
||||
|
||||
const saved = await saveProject(draft.dir, join(root, "My Ad"));
|
||||
const target = join(root, "Archive", "Ad Folder");
|
||||
const moved = await moveProject(saved.dir, target);
|
||||
expect(moved).toMatchObject({ id: draft.id, dir: target, name: "Ad Folder", displayName: "My Ad", draft: false });
|
||||
expect(await readdir(root)).not.toContain("My Ad");
|
||||
});
|
||||
});
|
||||
@ -1,51 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// A project folder renamed or moved in Finder is found again next to where it
|
||||
// was, by the id in its record.
|
||||
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: { isPackaged: false, getPath: () => tmpdir() },
|
||||
dialog: {},
|
||||
shell: {},
|
||||
ipcMain: { on: () => { } },
|
||||
}));
|
||||
|
||||
const { findMovedProject, initProject } = await import("./projects");
|
||||
|
||||
let root: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), "locate-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("findMovedProject", () => {
|
||||
it("finds a project renamed in place by its id", async () => {
|
||||
const project = await initProject(null, join(root, "golden-river"));
|
||||
await initProject(null, join(root, "another"));
|
||||
await rename(project.dir, join(root, "My Ad"));
|
||||
|
||||
const found = await findMovedProject(project.dir, project.id);
|
||||
expect(found).toMatchObject({ id: project.id, dir: join(root, "My Ad") });
|
||||
});
|
||||
|
||||
it("finds nothing when the folder left its parent, or the parent is gone", async () => {
|
||||
const project = await initProject(null, join(root, "golden-river"));
|
||||
await mkdir(join(root, "elsewhere", "deeper"), { recursive: true });
|
||||
await rename(project.dir, join(root, "elsewhere", "deeper", "My Ad"));
|
||||
|
||||
expect(await findMovedProject(project.dir, project.id)).toBeNull();
|
||||
expect(await findMovedProject(join(root, "gone", "golden-river"), project.id)).toBeNull();
|
||||
expect(await findMovedProject(project.dir, "")).toBeNull();
|
||||
});
|
||||
});
|
||||
@ -16,13 +16,11 @@ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
|
||||
import type { PluginItem, TransformOptions } from "@babel/core";
|
||||
import type { BuildOptions, Plugin } from "esbuild";
|
||||
|
||||
import { countCodeChange } from "./analytics";
|
||||
import { isTempPath, TEMP_PREFIX, writeFileAtomic } from "./atomic";
|
||||
import { windowsCloudSyncKind } from "./cloud-sync-windows";
|
||||
import { isHeadless } from "./headless";
|
||||
import { mainBridge } from "./main-manager";
|
||||
import { MAIN_CHANNELS } from "./main-channels";
|
||||
import { applyEdits, editLabel, stampProject } from "./edit";
|
||||
import { migrateGenerations } from "./legacy-generations";
|
||||
import { canonicalizeTagsPlugin, inspectPlugin, sourcePlugin } from "./source";
|
||||
import type { CompileResult, FsEntry, FsStat, ProjectInfo, SourceEdit, WriteResult } from "./main-channels";
|
||||
import type { SourceContext } from "./edit";
|
||||
@ -98,8 +96,7 @@ async function writePackage(dir: string, pkg: PackageJson): Promise<void> {
|
||||
// Identity
|
||||
|
||||
// A project is named twice: `displayName` is what the user calls it and the
|
||||
// folder is what the disk calls it, and either can change apart from the
|
||||
// other (the app renames the one, the user moves the other). Neither can be
|
||||
// folder is what the disk calls it, and renaming moves both. Neither can be
|
||||
// the project's identity, so the record carries an id that nothing renames —
|
||||
// it is what the app's URLs point at, and what the editor keys the open world
|
||||
// by. Top level rather than inside `diffusion`, which `writeConfig` replaces
|
||||
@ -154,121 +151,54 @@ async function describe(dir: string): Promise<ProjectInfo | null> {
|
||||
entry,
|
||||
modifiedAt: file.mtime.toISOString(),
|
||||
createdAt: folder.birthtime.toISOString(),
|
||||
draft: isDraft(dir),
|
||||
};
|
||||
}
|
||||
|
||||
export const getProject = (dir: string): Promise<ProjectInfo | null> => describe(dir);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Drafts
|
||||
|
||||
// A new project starts as a draft: a folder the app makes without asking,
|
||||
// in a place of its own, named after the id. Saving it (⌘S) is when the user
|
||||
// says where it goes and what the folder is called — the folder moves there,
|
||||
// and from then on it is an ordinary project.
|
||||
|
||||
/**
|
||||
* The folder drafts live in. Inside the app's own data, which nothing syncs —
|
||||
* neither iCloud nor OneDrive reaches `Application Support` or `AppData` —
|
||||
* and which needs no permission prompt. On Windows the Local AppData rather
|
||||
* than the Roaming one, which a roaming profile would carry, media and all,
|
||||
* from machine to machine.
|
||||
* The folder projects go in when the user has not picked one. `~/Movies` on
|
||||
* macOS, `Videos` elsewhere — chosen because it is the one media folder the
|
||||
* sync services leave alone: iCloud's "Desktop & Documents Folders" covers
|
||||
* only those two, and OneDrive's Known Folder Move only Desktop, Documents,
|
||||
* and Pictures. It also needs no macOS permission prompt, which Documents and
|
||||
* Desktop do. Created on demand, so a user who never makes a project never
|
||||
* gets the folder.
|
||||
*
|
||||
* Null when it turns out to be synced after all and the user would rather
|
||||
* pick somewhere else — the caller falls back to `pickRoot`.
|
||||
*/
|
||||
export function draftsRoot(): string {
|
||||
const local = process.platform === "win32" ? process.env.LOCALAPPDATA : undefined;
|
||||
const base = local ? join(local, basename(app.getPath("userData"))) : app.getPath("userData");
|
||||
return join(base, "Drafts");
|
||||
}
|
||||
|
||||
/** Whether `dir` is a draft's folder: directly inside `draftsRoot`. */
|
||||
function isDraft(dir: string): boolean {
|
||||
const parent = dirname(resolve(dir));
|
||||
const root = draftsRoot();
|
||||
return process.platform === "win32" ? parent.toLowerCase() === root.toLowerCase() : parent === root;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the save picker starts when no project has been saved yet: a folder
|
||||
* under `~/Movies` on macOS, `Videos` elsewhere — the one media folder the
|
||||
* sync services leave alone (iCloud's "Desktop & Documents Folders" covers
|
||||
* only those two, OneDrive's Known Folder Move only Desktop, Documents, and
|
||||
* Pictures), and one that needs no macOS permission prompt. Created on
|
||||
* demand, so a user who never saves a project never gets the folder.
|
||||
*/
|
||||
async function defaultSaveFolder(): Promise<string> {
|
||||
export async function defaultRoot(window: BrowserWindow | null): Promise<string | null> {
|
||||
const dir = join(app.getPath("videos"), "Diffusion Studio");
|
||||
if (!(await confirmCloudLocation(window, dir, "Choose another folder"))) return null;
|
||||
await mkdir(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** Characters no folder name can hold on one platform or another. */
|
||||
const UNSAFE_NAME = /[\\/:*?"<>|]+/g;
|
||||
|
||||
/** Why the project in `dir` cannot be saved or moved as `target`, or null when it can. */
|
||||
async function saveProblem(dir: string, target: string): Promise<string | null> {
|
||||
if (await exists(target)) {
|
||||
return `"${basename(target)}" already exists in ${basename(dirname(target))}. Choose another name.`;
|
||||
}
|
||||
const inside = relative(resolve(dir), resolve(target));
|
||||
if (!inside.startsWith("..") && !isAbsolute(inside)) return "A project can't be saved inside itself.";
|
||||
if (isDraft(target)) return "Choose a folder outside the drafts folder.";
|
||||
return null;
|
||||
}
|
||||
|
||||
/** What the save picker is asked for: saving a draft, or moving a saved project. */
|
||||
export type SaveAction = "save" | "move";
|
||||
|
||||
/**
|
||||
* Asks where to save the draft in `dir`, or where to move the project there:
|
||||
* the folder it will become, or null when the user cancels. Starts in
|
||||
* `startIn` — the parent of the last project saved — with `name` filled in.
|
||||
* A name that is taken is refused rather than replaced, and a synced folder
|
||||
* is warned about; either way the picker comes back, since the user came here
|
||||
* to save.
|
||||
*/
|
||||
export async function pickSaveLocation(
|
||||
window: BrowserWindow | null,
|
||||
dir: string,
|
||||
name: string,
|
||||
startIn: string | null,
|
||||
action: SaveAction = "save",
|
||||
): Promise<string | null> {
|
||||
const start = startIn && (await stat(startIn).catch(() => null))?.isDirectory() ? startIn : await defaultSaveFolder();
|
||||
const folder = name.replace(UNSAFE_NAME, "-").trim() || basename(dir);
|
||||
const options: Electron.SaveDialogOptions = {
|
||||
title: action === "move" ? "Move project" : "Save project",
|
||||
buttonLabel: action === "move" ? "Move" : "Save",
|
||||
defaultPath: join(start, folder),
|
||||
properties: ["createDirectory", "showOverwriteConfirmation"],
|
||||
export async function pickRoot(window: BrowserWindow | null): Promise<string | null> {
|
||||
const options: Electron.OpenDialogOptions = {
|
||||
title: "Choose projects folder",
|
||||
defaultPath: app.getPath("videos"),
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
};
|
||||
|
||||
// Declining a synced folder reopens the picker rather than dropping the
|
||||
// user back to the dashboard: they came here to choose one.
|
||||
while (true) {
|
||||
const { canceled, filePath } = window
|
||||
? await dialog.showSaveDialog(window, options)
|
||||
: await dialog.showSaveDialog(options);
|
||||
if (canceled || !filePath) return null;
|
||||
options.defaultPath = filePath;
|
||||
|
||||
const problem = await saveProblem(dir, filePath);
|
||||
if (problem) {
|
||||
const message: Electron.MessageBoxOptions = {
|
||||
type: "warning",
|
||||
message: action === "move" ? "Can't move here" : "Can't save here",
|
||||
detail: problem,
|
||||
};
|
||||
if (window) await dialog.showMessageBox(window, message);
|
||||
else await dialog.showMessageBox(message);
|
||||
continue;
|
||||
const { canceled, filePaths } = window
|
||||
? await dialog.showOpenDialog(window, options)
|
||||
: await dialog.showOpenDialog(options);
|
||||
if (canceled || !filePaths[0]) return null;
|
||||
if (await confirmCloudLocation(window, filePaths[0], "Choose another folder")) {
|
||||
return filePaths[0];
|
||||
}
|
||||
if (await confirmCloudLocation(window, filePath, "Choose another folder")) return filePath;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A folder to open as a single project, wherever it lives. It does not vet
|
||||
* the location: the folder goes through `initProject`, which asks about a
|
||||
* synced one there.
|
||||
* A folder to open as a single project, wherever it lives. Unlike `pickRoot`
|
||||
* this leaves the projects root alone, and it does not vet the location: the
|
||||
* folder goes through `initProject`, which asks about a synced one there.
|
||||
*/
|
||||
export async function pickFolder(window: BrowserWindow | null): Promise<string | null> {
|
||||
const options: Electron.OpenDialogOptions = {
|
||||
@ -388,8 +318,18 @@ export async function cloudSyncKind(path: string): Promise<string | null> {
|
||||
const mobile = await resolveDeepest(join(home, "Library", "Mobile Documents"));
|
||||
if (real === mobile || real.startsWith(mobile + sep)) return "iCloud Drive";
|
||||
|
||||
// Windows has no File Provider to ask; everything below is macOS.
|
||||
if (process.platform === "win32") return windowsCloudSyncKind(real, home);
|
||||
// Windows has no File Provider to ask.
|
||||
if (process.platform === "win32") {
|
||||
const roots: Array<[string, string]> = [[join(home, "iCloudDrive"), "iCloud Drive"]];
|
||||
for (const key of ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"]) {
|
||||
const dir = process.env[key];
|
||||
if (dir) roots.push([dir, "OneDrive"]);
|
||||
}
|
||||
for (const [dir, label] of roots) {
|
||||
const root = resolve(dir);
|
||||
if (real === root || real.startsWith(root + sep)) return label;
|
||||
}
|
||||
}
|
||||
|
||||
// The home Desktop and Documents, before the attribute is asked for: it is
|
||||
// the one the app is most likely to be unable to read.
|
||||
@ -413,8 +353,8 @@ export async function cloudSyncKind(path: string): Promise<string | null> {
|
||||
/**
|
||||
* Whether to go ahead with `path`: true when nothing syncs it, and when the
|
||||
* user has been told what syncing does to a project and wants it anyway.
|
||||
* Nobody is asked while the window is hidden — an agent is driving and there
|
||||
* is nobody to ask — and the project goes ahead with the warning in the log.
|
||||
* Headless runs are never asked — there is nobody to ask — and proceed with
|
||||
* the warning in the log.
|
||||
*/
|
||||
async function confirmCloudLocation(
|
||||
window: BrowserWindow | null,
|
||||
@ -424,7 +364,7 @@ async function confirmCloudLocation(
|
||||
const kind = await cloudSyncKind(path);
|
||||
if (!kind) return true;
|
||||
|
||||
if (!window?.isVisible()) {
|
||||
if (isHeadless()) {
|
||||
console.warn(`[projects] ${path} is synced by ${kind}; projects there may misbehave`);
|
||||
return true;
|
||||
}
|
||||
@ -449,52 +389,24 @@ async function confirmCloudLocation(
|
||||
return response === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* The project `id` in a folder beside `dir`, which no longer holds it: one
|
||||
* renamed in Finder, or moved to another folder next to it. Found by the id in
|
||||
* its record, which goes wherever the folder goes. Null when no sibling holds
|
||||
* it, or `dir`'s parent is gone too. Reads only.
|
||||
*/
|
||||
export async function findMovedProject(dir: string, id: string): Promise<ProjectInfo | null> {
|
||||
if (!id) return null;
|
||||
const parent = dirname(dir);
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(parent, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
for (const entry of entries) {
|
||||
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
|
||||
const candidate = join(parent, entry.name);
|
||||
if (recordedId(await readPackage(candidate)) === id) return describe(candidate);
|
||||
}
|
||||
return null;
|
||||
/** Direct child folders of `root` that could hold a project, in a stable order. */
|
||||
async function childDirs(root: string): Promise<string[]> {
|
||||
const entries = await readdir(root, { withFileTypes: true });
|
||||
return entries
|
||||
.filter((entry) => entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== "node_modules")
|
||||
.map((entry) => entry.name)
|
||||
.sort()
|
||||
.map((name) => join(root, name));
|
||||
}
|
||||
|
||||
/** What the user wants done about a project whose folder can't be found. */
|
||||
export type MissingProjectChoice = "locate" | "remove" | "cancel";
|
||||
|
||||
/** Tells the user the project's folder is gone, and asks what to do about it. */
|
||||
export async function askAboutMissingProject(
|
||||
window: BrowserWindow | null,
|
||||
displayName: string,
|
||||
dir: string,
|
||||
): Promise<MissingProjectChoice> {
|
||||
const options: Electron.MessageBoxOptions = {
|
||||
type: "warning",
|
||||
message: `Can't find "${displayName}"`,
|
||||
detail: `It was in ${dir}. It may have been moved, renamed or deleted, or be on a disk that isn't connected.`,
|
||||
buttons: ["Locate...", "Remove from List", "Cancel"],
|
||||
defaultId: 0,
|
||||
cancelId: 2,
|
||||
};
|
||||
const { response } = window
|
||||
? await dialog.showMessageBox(window, options)
|
||||
: await dialog.showMessageBox(options);
|
||||
if (response === 0) return "locate";
|
||||
if (response === 1) return "remove";
|
||||
return "cancel";
|
||||
/**
|
||||
* Every direct child folder of `root` that holds an entry file. The one
|
||||
* search of the disk for projects there is: the app runs it when a projects
|
||||
* root is chosen, to put the projects already in it on its list. Reads only.
|
||||
*/
|
||||
export async function scanProjects(root: string): Promise<ProjectInfo[]> {
|
||||
const projects = await Promise.all((await childDirs(root)).map(describe));
|
||||
return projects.filter((project): project is ProjectInfo => project !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -513,6 +425,17 @@ export async function resolveProject(dir: string): Promise<ProjectInfo | null> {
|
||||
// ---------------------------------------------------------------------------
|
||||
// Scaffold
|
||||
|
||||
/** Folder-safe project name: "Golden River 15 Aug" -> "golden-river-15-aug". */
|
||||
function folderName(name: string): string {
|
||||
return (
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9._-]+/g, "-")
|
||||
.replace(/^[-.]+|[-.]+$/g, "")
|
||||
.slice(0, 64) || "project"
|
||||
);
|
||||
}
|
||||
|
||||
/** `base`, or `base-2`, `base-3`... when the folder is taken. */
|
||||
async function freeFolder(root: string, base: string): Promise<string> {
|
||||
let name = base;
|
||||
@ -535,25 +458,29 @@ const JSX_VERSION = "latest";
|
||||
const SOLID_VERSION = "^1.9.10";
|
||||
|
||||
/**
|
||||
* The diffusion surface as npm scripts: the CLI is how a project is inspected and
|
||||
* The dapi surface as npm scripts: the CLI is how a project is inspected and
|
||||
* cut, so its commands belong in the record of the project they act on —
|
||||
* `npm run` prints the menu, `npm run <name> -- <args>` runs one, named after
|
||||
* the command.
|
||||
* `npm run` prints the menu, `npm run <name> -- <args>` runs one. Named after
|
||||
* the command rather than its path (`grab`, not `media:grab`): the `media`
|
||||
* subcommands have no top-level namesakes to collide with.
|
||||
*/
|
||||
const SCRIPTS: Record<string, string> = {
|
||||
open: "diffusion open .",
|
||||
context: "diffusion context",
|
||||
capture: "diffusion capture",
|
||||
probe: "diffusion probe",
|
||||
transcribe: "diffusion transcribe",
|
||||
grab: "diffusion grab",
|
||||
filmstrip: "diffusion filmstrip",
|
||||
waveform: "diffusion waveform",
|
||||
listen: "diffusion listen",
|
||||
fonts: "diffusion fonts",
|
||||
logs: "diffusion logs",
|
||||
screenshot: "diffusion screenshot",
|
||||
report: "diffusion report",
|
||||
open: "dapi open .",
|
||||
context: "dapi context",
|
||||
capture: "dapi capture",
|
||||
probe: "dapi media probe",
|
||||
transcribe: "dapi media transcribe",
|
||||
grab: "dapi media grab",
|
||||
filmstrip: "dapi media filmstrip",
|
||||
waveform: "dapi media waveform",
|
||||
listen: "dapi media listen",
|
||||
models: "dapi models",
|
||||
voices: "dapi voices",
|
||||
fonts: "dapi fonts",
|
||||
whoami: "dapi whoami",
|
||||
logs: "dapi logs",
|
||||
screenshot: "dapi screenshot",
|
||||
report: "dapi report",
|
||||
};
|
||||
|
||||
const packageJson = (name: string, displayName: string): PackageJson => ({
|
||||
@ -623,7 +550,7 @@ on the canvas.
|
||||
|
||||
## Agents
|
||||
|
||||
Everything an agent needs is in the app's MCP server (\`diffusion\`): its tools
|
||||
Everything an agent needs is in the app's MCP server (\`dapi\`): its tools
|
||||
are the API, its instructions say how to work, and its resources are the
|
||||
authoring reference for the installed version. If it is not among your tools,
|
||||
add it — the app serves it at \`${MCP_URL}\` while it is running — and start
|
||||
@ -634,10 +561,10 @@ a new session.
|
||||
| Path | What it is |
|
||||
| ---- | ---------- |
|
||||
| \`index.tsx\` | The entry. Its default export renders the composition. |
|
||||
| \`package.json\` | The project record: \`projectId\` (its identity, kept across renames), \`displayName\` (the name shown in the app), \`main\` (the entry), \`diffusion\` (how each scene is exported, and whether the stage has ever had anything on it), and the diffusion commands as scripts. |
|
||||
| \`package.json\` | The project record: \`projectId\` (its identity, kept across renames), \`displayName\` (the name shown in the app), \`main\` (the entry), \`diffusion\` (how each scene is exported), and the dapi commands as scripts. |
|
||||
| \`tsconfig.json\` | Types for the composition tags, through \`jsxImportSource\`. |
|
||||
| \`assets.yml\` | The asset library: for every asset its library path, where its bytes are, and what it was found to be. Written by the app; hand edits are read on the next load. |
|
||||
| \`assets/\` | The library's files: put one here and it is taken in while the app watches, and the app writes its own here too. Media imported through the app is linked where it lies instead, never copied. |
|
||||
| \`assets.yml\` | The asset library: for every asset its library path, where its bytes are, and what it was found to be; for a generation without bytes, where it stands. Written by the app; hand edits are read on the next load. |
|
||||
| \`assets/\` | The library's files: put one here and it is taken in while the app watches, and the app writes its own here too — generations under \`assets/generated/\`. Media imported through the app is linked where it lies instead, never copied. |
|
||||
| \`cache/\` | Derived data (thumbnails, waveforms). Disposable, and not checked in. |
|
||||
|
||||
## Authoring
|
||||
@ -683,6 +610,10 @@ export default function Project() {
|
||||
and the gradient paints, \`<stroke>\`, \`<shadow>\`, \`<effect>\`.
|
||||
- \`src\` takes a library path (\`"b-roll/drone.mp4"\` — the portable form, it
|
||||
survives the file being relinked), an asset id, a URL, or an absolute path.
|
||||
- Generated assets are declared rather than fetched: \`src={generate.image({ prompt })}\`,
|
||||
and \`generate.video\`, \`generate.voice\`, \`generate.audio\`. They are produced on
|
||||
mount, in dependency order. \`dapi context\` reports where each stands:
|
||||
generating, failed with the reason, or done with the asset path it landed as.
|
||||
- Solid is fully available while mounting: \`<For>\`, \`<Show>\`, \`createMemo\`, and
|
||||
\`useTicker()\` for values that follow the playhead.
|
||||
- npm packages work as they normally do. The folder is a real npm package, so
|
||||
@ -695,29 +626,32 @@ yourself with \`npx tsc --noEmit\`.
|
||||
|
||||
## Commands
|
||||
|
||||
Every diffusion command is a script here: \`npm run\` lists them, and
|
||||
Every dapi command is a script here: \`npm run\` lists them, and
|
||||
\`npm run <name> -- <args>\` runs one (\`npm run grab -- b-roll/drone.mp4 -c 6\`).
|
||||
All of them talk to the running app, except \`fonts\`.
|
||||
|
||||
| Script | Command | What it does |
|
||||
| ------ | ------- | ------------ |
|
||||
| \`open\` | \`diffusion open .\` | Launch the app with this project open. |
|
||||
| \`context\` | \`diffusion context\` | Which project the app has open, where its playhead sits, its fonts, its background mask tracks. |
|
||||
| \`capture\` | \`diffusion capture <id>\` | Render frames of a scene, as an export would, to labelled PNG contact sheets. |
|
||||
| \`probe\` | \`diffusion probe <id\\|path>\` | Container and per-track metadata, without decoding. |
|
||||
| \`transcribe\` | \`diffusion transcribe <id\\|path>\` | Timed speech transcript, word by word. |
|
||||
| \`grab\` | \`diffusion grab <id\\|path>\` | Decode frames of a video to labelled PNG contact sheets. |
|
||||
| \`filmstrip\` | \`diffusion filmstrip <id\\|path>\` | Thumbnail grid across a window of a video. |
|
||||
| \`waveform\` | \`diffusion waveform <id\\|path>\` | Loudness over time, with the silences marked. |
|
||||
| \`listen\` | \`diffusion listen <id\\|path>\` | Ask a multimodal model what is in an audio track. |
|
||||
| \`fonts\` | \`diffusion fonts\` | Google Fonts and local font families, valid as \`fontFamily\`. |
|
||||
| \`logs\` | \`diffusion logs\` | Recent console output from the app. |
|
||||
| \`screenshot\` | \`diffusion screenshot\` | The whole app window as a PNG. |
|
||||
| \`report\` | \`diffusion report <title>\` | File a bug against the editor, with diagnostics attached. |
|
||||
| \`open\` | \`dapi open .\` | Launch the app with this project open. |
|
||||
| \`context\` | \`dapi context\` | Which project the app has open, where its playhead sits, its fonts, where its generations stand. |
|
||||
| \`capture\` | \`dapi capture <id>\` | Render frames of a scene, as an export would, to labelled PNG contact sheets. |
|
||||
| \`probe\` | \`dapi media probe <id\\|path>\` | Container and per-track metadata, without decoding. |
|
||||
| \`transcribe\` | \`dapi media transcribe <id\\|path>\` | Timed speech transcript, word by word. |
|
||||
| \`grab\` | \`dapi media grab <id\\|path>\` | Decode frames of a video to labelled PNG contact sheets. |
|
||||
| \`filmstrip\` | \`dapi media filmstrip <id\\|path>\` | Thumbnail grid across a window of a video. |
|
||||
| \`waveform\` | \`dapi media waveform <id\\|path>\` | Loudness over time, with the silences marked. |
|
||||
| \`listen\` | \`dapi media listen <id\\|path>\` | Ask a multimodal model what is in an audio track. |
|
||||
| \`models\` | \`dapi models [type]\` | Generation models and their per-model constraints. |
|
||||
| \`voices\` | \`dapi voices\` | Speech voices for \`generate.voice\`. |
|
||||
| \`fonts\` | \`dapi fonts\` | Local font families, valid as \`fontFamily\`. |
|
||||
| \`whoami\` | \`dapi whoami\` | The signed-in account. |
|
||||
| \`logs\` | \`dapi logs\` | Recent console output from the app. |
|
||||
| \`screenshot\` | \`dapi screenshot\` | The whole app window as a PNG. |
|
||||
| \`report\` | \`dapi report <title>\` | File a bug against the editor, with diagnostics attached. |
|
||||
|
||||
## Reference
|
||||
|
||||
- [JSX reference](https://github.com/diffusionstudio/editor/blob/main/docs/reference/jsx/README.md): elements, timing, paints, captions
|
||||
- [JSX reference](https://github.com/diffusionstudio/editor/blob/main/docs/reference/jsx/README.md): elements, timing, paints, generation, captions
|
||||
- [Tool reference](https://github.com/diffusionstudio/editor/blob/main/docs/reference/tools/README.md): every tool and command, its options and its output
|
||||
- [Examples](https://github.com/diffusionstudio/editor/tree/main/docs/examples): runnable compositions to read
|
||||
`;
|
||||
@ -751,7 +685,7 @@ async function ensurePackage(dir: string, name: string, displayName: string, ent
|
||||
if (typeof next.displayName !== "string") next.displayName = displayName;
|
||||
if (typeof next.main !== "string") next.main = entry;
|
||||
// The commands are a menu rather than a record: a project that keeps its own
|
||||
// scripts is left with them, one with none is given the diffusion surface.
|
||||
// scripts is left with them, one with none is given the dapi surface.
|
||||
if (typeof next.scripts !== "object" || next.scripts === null) next.scripts = { ...SCRIPTS };
|
||||
if (
|
||||
next.projectId !== pkg.projectId ||
|
||||
@ -806,7 +740,7 @@ async function ensureRecord(dir: string, displayName = basename(dir)): Promise<s
|
||||
* .gitignore, which come with a project created from the dashboard (see
|
||||
* `scaffold`); a folder opened from anywhere on disk stays the user's. A
|
||||
* folder that is already a project comes back untouched. How
|
||||
* `diffusion open <path>` opens a folder.
|
||||
* `dapi open <path>` opens a folder.
|
||||
*/
|
||||
export async function initProject(window: BrowserWindow | null, dir: string): Promise<ProjectInfo> {
|
||||
if (!isAbsolute(dir)) {
|
||||
@ -827,59 +761,82 @@ export async function initProject(window: BrowserWindow | null, dir: string): Pr
|
||||
return project;
|
||||
}
|
||||
|
||||
/** What a new project is called until it is saved under a name of the user's. */
|
||||
const DRAFT_NAME = "Untitled";
|
||||
|
||||
/**
|
||||
* Creates a fresh project as a draft: a folder in `draftsRoot` named after
|
||||
* the id it is given here, so creating one asks nothing. `saveProject` is
|
||||
* what gives it a place and a name of the user's choosing.
|
||||
* Creates a fresh project folder under `root`, named after `displayName`. A
|
||||
* taken name is numbered rather than refused: the folder is a label, the id
|
||||
* inside it is the project.
|
||||
*/
|
||||
export async function createProject(): Promise<ProjectInfo> {
|
||||
const id = nanoid();
|
||||
const dir = join(draftsRoot(), id);
|
||||
export async function createProject(root: string, displayName: string): Promise<ProjectInfo> {
|
||||
const dir = join(root, await freeFolder(root, folderName(displayName)));
|
||||
await mkdir(dir, { recursive: true });
|
||||
// The record first, so the scaffold keeps the id the folder is named after.
|
||||
await writePackage(dir, { ...packageJson(DRAFT_NAME, DRAFT_NAME), projectId: id });
|
||||
await scaffold(dir, DRAFT_NAME);
|
||||
await scaffold(dir, displayName);
|
||||
const project = await describe(dir);
|
||||
if (!project) throw new Error("Failed to scaffold the project.");
|
||||
return project;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renames the project: the human name in the record, and nothing else. The
|
||||
* folder keeps its name — moving it is the user's to do, by hand — and the id
|
||||
* the project goes by is untouched either way.
|
||||
* Renames the project: the human name in the record, and the folder with it,
|
||||
* so what the user sees in Finder keeps matching what they see in the app.
|
||||
* This is the only thing here that moves a folder — nothing syncs the two
|
||||
* behind the user's back — and it costs the project neither its identity nor
|
||||
* its links, both of which are the id.
|
||||
*/
|
||||
export async function renameProject(dir: string, displayName: string): Promise<ProjectInfo> {
|
||||
const pkg = (await readPackage(dir)) ?? packageJson(basename(dir), displayName);
|
||||
await writePackage(dir, { ...pkg, displayName: displayName.trim() || basename(dir) });
|
||||
const name = displayName.trim() || basename(dir);
|
||||
await writePackage(dir, { ...pkg, displayName: name });
|
||||
|
||||
const project = await describe(dir);
|
||||
const project = await describe(await renameFolder(dir, name));
|
||||
if (!project) throw new Error("Not a project folder.");
|
||||
return project;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the folder next to itself as `<name>-copy` (numbered when taken); a
|
||||
* draft's copy is a draft too, named after its own id.
|
||||
* Moves the project folder to match `displayName`; answers where it ended up.
|
||||
* Best effort by design: the folder can be locked, open elsewhere, or on a
|
||||
* volume that will not have it, and none of that should cost the user the
|
||||
* name they just typed.
|
||||
*/
|
||||
async function renameFolder(dir: string, displayName: string): Promise<string> {
|
||||
const root = dirname(dir);
|
||||
const base = folderName(displayName);
|
||||
const current = basename(dir);
|
||||
// Already named after it, numbered suffix and all: moving `my-clip-2` to
|
||||
// `my-clip` (or to `my-clip-3`) shuffles folders that are equally right.
|
||||
if (current === base || (current.startsWith(`${base}-`) && /^\d+$/.test(current.slice(base.length + 1)))) {
|
||||
return dir;
|
||||
}
|
||||
|
||||
try {
|
||||
const target = join(root, await freeFolder(root, base));
|
||||
// The watcher holds the old path, and the renderer re-watches the new one
|
||||
// as soon as it hears where the project went.
|
||||
unwatchProject(dir);
|
||||
await rename(dir, target);
|
||||
return target;
|
||||
} catch {
|
||||
return dir;
|
||||
}
|
||||
}
|
||||
|
||||
/** Copies the folder next to itself as `<name>-copy` (numbered when taken). */
|
||||
export async function duplicateProject(dir: string): Promise<ProjectInfo> {
|
||||
const source = await describe(dir);
|
||||
if (!source) throw new Error("Not a project folder.");
|
||||
|
||||
const id = nanoid();
|
||||
const root = dirname(dir);
|
||||
const target = source.draft ? join(root, id) : join(root, await freeFolder(root, `${source.name}-copy`));
|
||||
const target = join(root, await freeFolder(root, `${source.name}-copy`));
|
||||
|
||||
await cp(dir, target, { recursive: true, errorOnExist: true, force: false });
|
||||
// The record came along with everything else, id included, and two folders
|
||||
// answering to one id is the thing the id exists to prevent.
|
||||
// answering to one id is the thing the id exists to prevent. The folder is
|
||||
// already named for the copy, so the record is written here rather than
|
||||
// through `renameProject` (which would move it again).
|
||||
const pkg = await readPackage(target);
|
||||
await writePackage(target, {
|
||||
...(pkg ?? packageJson(basename(target), source.displayName)),
|
||||
projectId: id,
|
||||
projectId: nanoid(),
|
||||
displayName: `${source.displayName} (Copy)`,
|
||||
});
|
||||
const project = await describe(target);
|
||||
@ -887,61 +844,11 @@ export async function duplicateProject(dir: string): Promise<ProjectInfo> {
|
||||
return project;
|
||||
}
|
||||
|
||||
/**
|
||||
* Saves the draft in `dir` as `target`: moves its folder there and names the
|
||||
* project after it — the name the user typed in the save picker, which is
|
||||
* the draft's own unless they changed it. Writes still on their way into the
|
||||
* draft land first; whoever has it open lets go of the folder before asking
|
||||
* (see `ProjectProvider` in the web app), and opens it again where it went.
|
||||
*/
|
||||
export async function saveProject(dir: string, target: string): Promise<ProjectInfo> {
|
||||
if (!isDraft(dir)) throw new Error("This project is saved already.");
|
||||
await moveFolder(dir, target);
|
||||
return renameProject(target, basename(target));
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the saved project in `dir` to `target`, as saving moves a draft —
|
||||
* but it keeps its name, which is the user's already. A draft is saved
|
||||
* rather than moved.
|
||||
*/
|
||||
export async function moveProject(dir: string, target: string): Promise<ProjectInfo> {
|
||||
if (isDraft(dir)) throw new Error("Save the draft instead of moving it.");
|
||||
await moveFolder(dir, target);
|
||||
const project = await describe(target);
|
||||
if (!project) throw new Error("Failed to move the project.");
|
||||
return project;
|
||||
}
|
||||
|
||||
/** Moves the project folder `dir` to `target`, once whatever is on its way into it has landed. */
|
||||
async function moveFolder(dir: string, target: string): Promise<void> {
|
||||
if (!isAbsolute(target)) throw new Error(`The project folder must be an absolute path (got "${target}").`);
|
||||
const problem = await saveProblem(dir, target);
|
||||
if (problem) throw new Error(problem);
|
||||
|
||||
await settleWrites(dir);
|
||||
unwatchProject(dir);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
try {
|
||||
await rename(dir, target);
|
||||
} catch (error) {
|
||||
// Another volume: there is no moving a folder there, only copying it.
|
||||
if ((error as NodeJS.ErrnoException).code !== "EXDEV") throw error;
|
||||
await cp(dir, target, { recursive: true, errorOnExist: true, force: false });
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the folder to the trash; resolves with the id it had ("" for none), for what is kept outside it.
|
||||
* A folder that is already gone counts as deleted, so the project can still come off the list.
|
||||
*/
|
||||
/** Moves the folder to the trash; resolves with the id it had ("" for none), for what is kept outside it. */
|
||||
export async function deleteProject(dir: string): Promise<string> {
|
||||
const id = recordedId(await readPackage(dir));
|
||||
unwatchProject(dir);
|
||||
if (await exists(dir)) {
|
||||
await shell.trashItem(dir);
|
||||
}
|
||||
await shell.trashItem(dir);
|
||||
return id;
|
||||
}
|
||||
|
||||
@ -1016,11 +923,6 @@ export async function compileProject(dir: string): Promise<CompileResult> {
|
||||
// of the scaffold is the dashboard's (see `initProject`).
|
||||
await ensureRecord(dir);
|
||||
|
||||
// Projects from before generation was removed declare assets the JSX can
|
||||
// no longer load; they are pointed at what those declarations produced.
|
||||
// Writes nothing to a project with nothing left to migrate.
|
||||
await migrateGenerations(sourceContext(dir), await readManifest(dir).catch(() => null));
|
||||
|
||||
// Names every element before it is numbered, so the ids this compile hands
|
||||
// the canvas are durable ones. A fully keyed project is not written to.
|
||||
await stampProject(sourceContext(dir));
|
||||
@ -1062,47 +964,13 @@ export async function compileProject(dir: string): Promise<CompileResult> {
|
||||
* (see `noteContent`).
|
||||
*/
|
||||
export async function writeProject(dir: string, edits: SourceEdit[]): Promise<WriteResult> {
|
||||
const finish = startWrite(dir);
|
||||
try {
|
||||
return await applyEdits(sourceContext(dir), edits);
|
||||
} catch (error) {
|
||||
return { skipped: edits.map(editLabel), error: error instanceof Error ? error.message : String(error) };
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes into a project that have not finished yet, by folder. Saving a draft
|
||||
* moves its folder, and waits these out first (see `settleWrites`): one that
|
||||
* lost the race would fail, or put a file back in the folder that just left.
|
||||
* A write starts before its first await, so one asked for before the save is
|
||||
* always among them.
|
||||
*/
|
||||
const writes = new Map<string, Set<Promise<void>>>();
|
||||
|
||||
/** Marks a write into `dir` as running; call what it returns when the write is done. */
|
||||
function startWrite(dir: string): () => void {
|
||||
let release!: () => void;
|
||||
const done = new Promise<void>((resolve) => (release = resolve));
|
||||
const running = writes.get(dir) ?? new Set<Promise<void>>();
|
||||
writes.set(dir, running);
|
||||
running.add(done);
|
||||
|
||||
return () => {
|
||||
release();
|
||||
running.delete(done);
|
||||
if (!running.size && writes.get(dir) === running) {
|
||||
writes.delete(dir);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Settles once every write into `dir` asked for so far has, however it went. */
|
||||
async function settleWrites(dir: string): Promise<void> {
|
||||
await Promise.allSettled([...(writes.get(dir) ?? []), configWrites.get(dir)]);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Assets
|
||||
|
||||
@ -1138,16 +1006,11 @@ export async function readManifest(dir: string): Promise<unknown> {
|
||||
* claimed first so the watcher does not hand it back as a change.
|
||||
*/
|
||||
export async function writeManifest(dir: string, manifest: unknown): Promise<void> {
|
||||
const finish = startWrite(dir);
|
||||
try {
|
||||
const path = join(dir, MANIFEST_FILE);
|
||||
const text = `# Diffusion Studio asset library. Edited by the app; hand edits are read on the next load.
|
||||
const path = join(dir, MANIFEST_FILE);
|
||||
const text = `# Diffusion Studio asset library. Edited by the app; hand edits are read on the next load.
|
||||
${stringifyYaml(manifest, { lineWidth: 0 })}`;
|
||||
noteContent(path, text);
|
||||
await writeFileAtomic(path, text);
|
||||
} finally {
|
||||
finish();
|
||||
}
|
||||
noteContent(path, text);
|
||||
await writeFileAtomic(path, text);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -1162,37 +1025,17 @@ export async function readConfig(dir: string): Promise<unknown> {
|
||||
return pkg?.[CONFIG_FIELD] ?? null;
|
||||
}
|
||||
|
||||
/** Settles when the config write last asked for is done, by project. */
|
||||
const configWrites = new Map<string, Promise<void>>();
|
||||
|
||||
/**
|
||||
* Replaces the project's config in its package.json (removes the field for
|
||||
* null), leaving the rest of the record alone. The watcher is told to keep
|
||||
* quiet about it, like the manifest: the app already shows these values.
|
||||
*
|
||||
* One at a time, in the order asked: each reads the record the last one left,
|
||||
* and the file ends up holding the config the app was given last rather than
|
||||
* whichever write happened to finish last.
|
||||
*/
|
||||
export async function writeConfig(dir: string, config: unknown): Promise<void> {
|
||||
const previous = configWrites.get(dir);
|
||||
let release!: () => void;
|
||||
const done = new Promise<void>((resolve) => (release = resolve));
|
||||
configWrites.set(dir, done);
|
||||
|
||||
try {
|
||||
await previous;
|
||||
const pkg = (await readPackage(dir)) ?? packageJson(basename(dir), basename(dir));
|
||||
const next: PackageJson = { ...pkg };
|
||||
if (config === null || config === undefined) delete next[CONFIG_FIELD];
|
||||
else next[CONFIG_FIELD] = config;
|
||||
await writePackage(dir, next);
|
||||
} finally {
|
||||
release();
|
||||
if (configWrites.get(dir) === done) {
|
||||
configWrites.delete(dir);
|
||||
}
|
||||
}
|
||||
const pkg = (await readPackage(dir)) ?? packageJson(basename(dir), basename(dir));
|
||||
const next: PackageJson = { ...pkg };
|
||||
if (config === null || config === undefined) delete next[CONFIG_FIELD];
|
||||
else next[CONFIG_FIELD] = config;
|
||||
await writePackage(dir, next);
|
||||
}
|
||||
|
||||
/** Entries of a directory; [] when it is missing or not a directory. */
|
||||
@ -1290,8 +1133,8 @@ const watchers = new Map<string, FSWatcher>();
|
||||
|
||||
/**
|
||||
* What the app believes is on disk, by absolute path: a digest of the content
|
||||
* of every file whose write has been answered for (see `claimed`), and of
|
||||
* every change it has already been told about. The watcher stays on — anything else may be editing these files, and
|
||||
* of every file it has written, and of every change it has already been told
|
||||
* about. The watcher stays on — anything else may be editing these files, and
|
||||
* should still reach the canvas — but the app's own writes must not come back
|
||||
* as a change, or every key stamp and every dragged rect would cost a
|
||||
* recompile and a remount of the scene the user is looking at.
|
||||
@ -1305,36 +1148,6 @@ const watchers = new Map<string, FSWatcher>();
|
||||
*/
|
||||
const known = new Map<string, string>();
|
||||
|
||||
/**
|
||||
* Writes claimed that no event has answered for yet, oldest first, by absolute
|
||||
* path. More than one at a time: a slider writes the config on every move, so
|
||||
* the next write is claimed before the event for the last one is answered,
|
||||
* and that event must still be recognized as ours. One that matches settles
|
||||
* every claim made before it, which can no longer land after it.
|
||||
*/
|
||||
const claimed = new Map<string, string[]>();
|
||||
|
||||
/** Claims kept per path; past this the oldest is taken to have been answered. */
|
||||
const CLAIMS_MAX = 32;
|
||||
|
||||
function claim(path: string, digest: string): void {
|
||||
const claims = claimed.get(path) ?? [];
|
||||
claims.push(digest);
|
||||
if (claims.length > CLAIMS_MAX) claims.shift();
|
||||
claimed.set(path, claims);
|
||||
}
|
||||
|
||||
/** Whether `current` is what a claimed write put at `path`; settles it if so. */
|
||||
function settleClaim(path: string, current: string): boolean {
|
||||
const claims = claimed.get(path);
|
||||
const index = claims?.indexOf(current) ?? -1;
|
||||
if (index < 0) return false;
|
||||
claims!.splice(0, index + 1);
|
||||
if (!claims!.length) claimed.delete(path);
|
||||
known.set(path, current);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Digests for what has no content: a file that is not there, and a folder. */
|
||||
const ABSENT = "";
|
||||
const FOLDER = "folder";
|
||||
@ -1371,9 +1184,9 @@ async function digestOf(path: string): Promise<string> {
|
||||
* round, and self-correcting either way.
|
||||
*/
|
||||
export function noteContent(path: string, text: string | null): void {
|
||||
if (text === null) claim(path, ABSENT);
|
||||
if (text === null) known.set(path, ABSENT);
|
||||
else if (Buffer.byteLength(text) > DIGEST_MAX) known.delete(path);
|
||||
else claim(path, digest(text));
|
||||
else known.set(path, digest(text));
|
||||
}
|
||||
|
||||
/**
|
||||
@ -1387,12 +1200,9 @@ export function noteContent(path: string, text: string | null): void {
|
||||
* exactly what an event will find at `as`.
|
||||
*/
|
||||
export async function noteRenamed(temp: string, as: string): Promise<void> {
|
||||
claim(as, await digestOf(temp));
|
||||
known.set(as, await digestOf(temp));
|
||||
}
|
||||
|
||||
/** The files a change to which counts as code being written, for analytics. */
|
||||
const SOURCE_FILE = /\.[cm]?[jt]sx?$/;
|
||||
|
||||
export function watchProject(window: BrowserWindow | null, dir: string): void {
|
||||
if (watchers.has(dir)) return;
|
||||
|
||||
@ -1404,11 +1214,6 @@ export function watchProject(window: BrowserWindow | null, dir: string): void {
|
||||
|
||||
const watcher = watch(dir, { recursive: true }, (_event, filename) => {
|
||||
if (!filename) return;
|
||||
// macOS's recursive FSEvents watch fires an extra notification for the
|
||||
// watched folder itself alongside the real one for whatever changed
|
||||
// inside it — and again once more, asynchronously, after the folder is
|
||||
// removed and the watcher closed. Neither names an actual project file.
|
||||
if (filename === basename(dir)) return;
|
||||
// Project-relative and `/`-separated; installs churn node_modules constantly.
|
||||
const path = filename.split(sep).join("/");
|
||||
if (path.startsWith("node_modules/") || path === "node_modules") return;
|
||||
@ -1421,10 +1226,8 @@ export function watchProject(window: BrowserWindow | null, dir: string): void {
|
||||
queue = queue
|
||||
.then(async () => {
|
||||
const current = await digestOf(file);
|
||||
if (settleClaim(file, current) || known.get(file) === current) return;
|
||||
if (known.get(file) === current) return;
|
||||
known.set(file, current);
|
||||
if (SOURCE_FILE.test(path) && current !== ABSENT) countCodeChange(path);
|
||||
|
||||
mainBridge.emit(window, MAIN_CHANNELS.PROJECTS_CHANGED, { dir, path });
|
||||
})
|
||||
.catch(() => { });
|
||||
@ -1440,7 +1243,6 @@ export function unwatchProject(dir: string): void {
|
||||
// remember: the next watch starts from a fresh load of the project anyway.
|
||||
const prefix = dir.endsWith(sep) ? dir : dir + sep;
|
||||
for (const path of known.keys()) if (path.startsWith(prefix)) known.delete(path);
|
||||
for (const path of claimed.keys()) if (path.startsWith(prefix)) claimed.delete(path);
|
||||
}
|
||||
|
||||
export function unwatchAll(): void {
|
||||
|
||||
@ -21,7 +21,7 @@ vi.mock("electron", () => ({
|
||||
ipcMain: { on: () => { } },
|
||||
}));
|
||||
|
||||
const { noteContent, noteRenamed, readConfig, unwatchProject, watchProject, writeConfig, writeManifest } = await import("./projects");
|
||||
const { noteContent, noteRenamed, unwatchProject, watchProject, writeManifest } = await import("./projects");
|
||||
|
||||
let dir: string;
|
||||
let changed: string[] = [];
|
||||
@ -181,37 +181,4 @@ describe("watchProject", () => {
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
});
|
||||
|
||||
// A slider in the export settings writes the config on every move, so the
|
||||
// next write is claimed before the event for the last one is answered.
|
||||
it("says nothing about config writes that overlap, and keeps the last", async () => {
|
||||
await writeFile(join(dir, "package.json"), `${JSON.stringify({ name: "p" }, null, 2)}\n`, "utf8");
|
||||
await waitFor("package.json");
|
||||
|
||||
changed = [];
|
||||
const writes: Promise<void>[] = [];
|
||||
for (let bitrate = 1; bitrate <= 40; bitrate++) {
|
||||
writes.push(writeConfig(dir, { export: { intro: { video: { bitrate } } } }));
|
||||
await settle(8);
|
||||
}
|
||||
await Promise.all(writes);
|
||||
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
expect(await readConfig(dir)).toEqual({ export: { intro: { video: { bitrate: 40 } } } });
|
||||
});
|
||||
|
||||
it("reports an outside edit that lands between two of the app's own", async () => {
|
||||
const file = join(dir, "index.tsx");
|
||||
noteContent(file, "ours\n");
|
||||
noteContent(file, "ours again\n");
|
||||
await writeFileAtomic(file, "ours\n");
|
||||
await writeFile(file, "theirs\n", "utf8");
|
||||
await waitFor("index.tsx");
|
||||
|
||||
changed = [];
|
||||
await writeFileAtomic(file, "ours again\n");
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@ -28,12 +28,10 @@ const COMPOSITION_COMPONENTS = new Map<string, string>(
|
||||
|
||||
// These composition names also exist in SVG. An SVG fragment is DOM content
|
||||
// only while it has an SVG container in the same JSX tree; elsewhere the tag
|
||||
// keeps its composition meaning. `<mask>` and `<clipPath>` are SVG containers
|
||||
// too, but as such they only ever sit in an `<svg>`, so they are not counted
|
||||
// as one: a composition `<mask>` keeps the shapes under it composition ones.
|
||||
const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "ellipse", "polygon", "path", "text", "image", "mask", "clipPath"]);
|
||||
// keeps its composition meaning.
|
||||
const AMBIGUOUS_SVG_TAGS: ReadonlySet<string> = new Set(["rect", "text", "image"]);
|
||||
const SVG_CONTAINERS: ReadonlySet<string> = new Set([
|
||||
"svg", "g", "defs", "symbol", "marker", "pattern",
|
||||
"svg", "g", "defs", "symbol", "marker", "mask", "clipPath", "pattern",
|
||||
"filter", "linearGradient", "radialGradient", "textPath", "tspan", "switch",
|
||||
]);
|
||||
|
||||
|
||||
@ -1,34 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Which launches are Squirrel housekeeping: only the four event flags, only
|
||||
// on Windows, and only as the first argument, where Squirrel puts them. A
|
||||
// deep link or `--hidden` in that position is a real launch.
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("electron", () => ({ app: { quit: () => {} } }));
|
||||
|
||||
const { squirrelEvent } = await import("./squirrel");
|
||||
|
||||
const exe = "C:\\Users\\me\\AppData\\Local\\DiffusionStudio\\app-1.0.0\\Diffusion Studio.exe";
|
||||
|
||||
describe("squirrelEvent", () => {
|
||||
it("recognises each event flag on Windows", () => {
|
||||
for (const flag of ["--squirrel-install", "--squirrel-updated", "--squirrel-uninstall", "--squirrel-obsolete"]) {
|
||||
expect(squirrelEvent([exe, flag, "1.0.0"], "win32")).toBe(flag);
|
||||
}
|
||||
});
|
||||
|
||||
it("treats the first run and ordinary launches as launches", () => {
|
||||
expect(squirrelEvent([exe, "--squirrel-firstrun"], "win32")).toBeNull();
|
||||
expect(squirrelEvent([exe], "win32")).toBeNull();
|
||||
expect(squirrelEvent([exe, "--hidden"], "win32")).toBeNull();
|
||||
expect(squirrelEvent([exe, "diffusion://auth?x=1"], "win32")).toBeNull();
|
||||
});
|
||||
|
||||
it("is never an event off Windows", () => {
|
||||
expect(squirrelEvent(["/Applications/Diffusion Studio.app/Contents/MacOS/Diffusion Studio", "--squirrel-install"], "darwin")).toBeNull();
|
||||
});
|
||||
});
|
||||
@ -1,79 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Squirrel.Windows starts the app once for each install, update, and
|
||||
// uninstall, with a `--squirrel-*` flag as the only argument, and expects it
|
||||
// to do its housekeeping and exit. That is the moment the Start Menu
|
||||
// shortcut is created and removed (through Squirrel's own Update.exe, one
|
||||
// folder up from the versioned app folder), where the `diffusion`/`dapi`
|
||||
// shims are pointed at the new version and taken away again, and where the
|
||||
// agents' MCP entries are taken out of their configs so no agent is left
|
||||
// calling an app that is gone.
|
||||
// `--squirrel-firstrun` is the ordinary first launch and is not an event.
|
||||
|
||||
import { app } from "electron";
|
||||
import { spawn } from "node:child_process";
|
||||
import { basename, resolve } from "node:path";
|
||||
|
||||
import { removeShim, removeShimFromPath, writeShim } from "./cli-windows";
|
||||
import { AGENT_TARGETS } from "./mcp-config";
|
||||
import { applyMcp } from "./mcp-install";
|
||||
|
||||
const EVENTS = new Set(["--squirrel-install", "--squirrel-updated", "--squirrel-uninstall", "--squirrel-obsolete"]);
|
||||
|
||||
/** The `--squirrel-*` event this launch is, or null when it is a real launch. */
|
||||
export function squirrelEvent(argv: string[] = process.argv, platform: string = process.platform): string | null {
|
||||
if (platform !== "win32") return null;
|
||||
const flag = argv[1];
|
||||
return flag && EVENTS.has(flag) ? flag : null;
|
||||
}
|
||||
|
||||
/** Runs Update.exe with `args` and quits once it is done. Quits at once if it cannot be started. */
|
||||
function updateExe(args: string[]): void {
|
||||
const exe = resolve(process.execPath, "..", "..", "Update.exe");
|
||||
let child;
|
||||
try {
|
||||
child = spawn(exe, args, { detached: true, stdio: "ignore", windowsHide: true });
|
||||
} catch {
|
||||
app.quit();
|
||||
return;
|
||||
}
|
||||
child.on("error", () => app.quit());
|
||||
child.on("close", () => app.quit());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a Squirrel event launch. Returns true when this launch was one —
|
||||
* the caller must then not open a window or start any service; the app
|
||||
* quits by itself once the housekeeping is done.
|
||||
*/
|
||||
export function handleSquirrelEvent(): boolean {
|
||||
const event = squirrelEvent();
|
||||
if (!event) return false;
|
||||
|
||||
const target = basename(process.execPath);
|
||||
switch (event) {
|
||||
case "--squirrel-install":
|
||||
case "--squirrel-updated":
|
||||
writeShim()
|
||||
.catch(() => { })
|
||||
.then(() => updateExe(["--createShortcut", target]));
|
||||
break;
|
||||
case "--squirrel-uninstall":
|
||||
try {
|
||||
applyMcp({ add: [], remove: AGENT_TARGETS.map((target) => target.id) });
|
||||
} catch {/* best effort */ }
|
||||
|
||||
removeShimFromPath()
|
||||
.catch(() => { })
|
||||
.then(() => removeShim())
|
||||
.catch(() => { })
|
||||
.then(() => updateExe(["--removeShortcut", target]));
|
||||
break;
|
||||
default:
|
||||
// --squirrel-obsolete: the version being replaced gets a last word; we have none.
|
||||
app.quit();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@ -1,203 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The app's one permanent presence: agents use the app in the background, so
|
||||
// the menu bar (macOS) or notification area (Windows) is where it shows that
|
||||
// it is running, that an agent is working in it, and where the user opens
|
||||
// the editor or quits.
|
||||
|
||||
import { basename } from "node:path";
|
||||
import { app, Menu, nativeImage, nativeTheme, Tray } from "electron";
|
||||
|
||||
import idle1x from "../assets/tray/idleTemplate.png";
|
||||
import idle2x from "../assets/tray/idleTemplate@2x.png";
|
||||
import busy1x from "../assets/tray/busyTemplate.png";
|
||||
import busy2x from "../assets/tray/busyTemplate@2x.png";
|
||||
import win1x from "../assets/tray/win.png";
|
||||
import win2x from "../assets/tray/win@2x.png";
|
||||
import menuOpen1x from "../assets/tray/menu/open.png";
|
||||
import menuOpen2x from "../assets/tray/menu/open@2x.png";
|
||||
import menuHide1x from "../assets/tray/menu/hide.png";
|
||||
import menuHide2x from "../assets/tray/menu/hide@2x.png";
|
||||
import menuReady1x from "../assets/tray/menu/ready.png";
|
||||
import menuReady2x from "../assets/tray/menu/ready@2x.png";
|
||||
import menuBusy1x from "../assets/tray/menu/busy.png";
|
||||
import menuBusy2x from "../assets/tray/menu/busy@2x.png";
|
||||
import menuProject1x from "../assets/tray/menu/project.png";
|
||||
import menuProject2x from "../assets/tray/menu/project@2x.png";
|
||||
import menuQuit1x from "../assets/tray/menu/quit.png";
|
||||
import menuQuit2x from "../assets/tray/menu/quit@2x.png";
|
||||
|
||||
import type { NativeImage } from "electron";
|
||||
|
||||
export type AppTrayDeps = {
|
||||
/** Whether the window is out for the user. */
|
||||
visible(): boolean;
|
||||
/** Whether a tool call is running. */
|
||||
active(): boolean;
|
||||
/** The project the editor last had open. */
|
||||
project(): string | null;
|
||||
show(): void;
|
||||
hide(): void;
|
||||
};
|
||||
|
||||
// Calls come in bursts of short ones; the icon stays busy this long after the
|
||||
// last so it does not flicker between them.
|
||||
const BUSY_LINGER = 1500;
|
||||
|
||||
function image(x1: Uint8Array, x2: Uint8Array, template: boolean): NativeImage {
|
||||
const icon = nativeImage.createFromBuffer(Buffer.from(x1), { scaleFactor: 1 });
|
||||
icon.addRepresentation({ scaleFactor: 2, buffer: Buffer.from(x2) });
|
||||
icon.setTemplateImage(template);
|
||||
return icon;
|
||||
}
|
||||
|
||||
type MenuIcon = "open" | "hide" | "ready" | "busy" | "project" | "quit";
|
||||
|
||||
// macOS draws SF Symbols in the menu's own color. Elsewhere the icons are
|
||||
// black masks (scripts/tray-menu-icons.sh) recolored to the menu's text.
|
||||
const SYMBOLS: Record<MenuIcon, string> = {
|
||||
open: "macwindow",
|
||||
hide: "eye.slash",
|
||||
ready: "checkmark.circle",
|
||||
busy: "sparkles",
|
||||
project: "folder",
|
||||
quit: "power",
|
||||
};
|
||||
|
||||
const MASKS: Record<MenuIcon, [Uint8Array, Uint8Array]> = {
|
||||
open: [menuOpen1x, menuOpen2x],
|
||||
hide: [menuHide1x, menuHide2x],
|
||||
ready: [menuReady1x, menuReady2x],
|
||||
busy: [menuBusy1x, menuBusy2x],
|
||||
project: [menuProject1x, menuProject2x],
|
||||
quit: [menuQuit1x, menuQuit2x],
|
||||
};
|
||||
|
||||
/** A mask's pixels filled with `rgb`, keeping its alpha; bitmaps are premultiplied BGRA. */
|
||||
function tinted(png: Uint8Array, [r, g, b]: number[]) {
|
||||
const mask = nativeImage.createFromBuffer(Buffer.from(png));
|
||||
const { width, height } = mask.getSize();
|
||||
const buffer = mask.toBitmap();
|
||||
for (let i = 0; i < buffer.length; i += 4) {
|
||||
const a = buffer[i + 3] / 255;
|
||||
buffer[i] = Math.round(b * a);
|
||||
buffer[i + 1] = Math.round(g * a);
|
||||
buffer[i + 2] = Math.round(r * a);
|
||||
}
|
||||
return { buffer, width, height };
|
||||
}
|
||||
|
||||
function menuIcon(name: MenuIcon, dark: boolean): NativeImage {
|
||||
if (process.platform === "darwin") return nativeImage.createMenuSymbol(SYMBOLS[name]);
|
||||
const color = dark ? [242, 242, 242] : [28, 28, 28];
|
||||
const icon = nativeImage.createEmpty();
|
||||
MASKS[name].forEach((png, i) => icon.addRepresentation({ scaleFactor: i + 1, ...tinted(png, color) }));
|
||||
return icon;
|
||||
}
|
||||
|
||||
export class AppTray {
|
||||
private readonly deps: AppTrayDeps;
|
||||
private tray: Tray | null = null;
|
||||
private idleIcon: NativeImage | null = null;
|
||||
private busyIcon: NativeImage | null = null;
|
||||
private busy = false;
|
||||
private lingerTimer: NodeJS.Timeout | null = null;
|
||||
private wasVisible = false;
|
||||
private toldStillRunning = false;
|
||||
private menuIcons = new Map<string, NativeImage>();
|
||||
|
||||
constructor(deps: AppTrayDeps) {
|
||||
this.deps = deps;
|
||||
}
|
||||
|
||||
/** Puts the icon up; call once the app is ready. */
|
||||
start(): void {
|
||||
if (process.platform === "darwin") {
|
||||
// Template images: macOS tints them to fit the menu bar.
|
||||
this.idleIcon = image(idle1x, idle2x, true);
|
||||
this.busyIcon = image(busy1x, busy2x, true);
|
||||
} else {
|
||||
this.idleIcon = this.busyIcon = image(win1x, win2x, false);
|
||||
}
|
||||
this.tray = new Tray(this.idleIcon);
|
||||
// macOS opens the menu on click; elsewhere the menu is the right click
|
||||
// and a click opens the editor.
|
||||
if (process.platform !== "darwin") this.tray.on("click", () => this.deps.show());
|
||||
nativeTheme.on("updated", this.onThemeUpdated);
|
||||
this.refresh();
|
||||
}
|
||||
|
||||
/** Brings the icon and menu up to date; call whenever what they show changes. */
|
||||
refresh(): void {
|
||||
const tray = this.tray;
|
||||
if (!tray) return;
|
||||
|
||||
this.updateBusy();
|
||||
const visible = this.deps.visible();
|
||||
const project = this.deps.project();
|
||||
const status = this.busy ? "An agent is working…" : "Ready for agents";
|
||||
|
||||
tray.setImage(this.busy ? this.busyIcon! : this.idleIcon!);
|
||||
tray.setToolTip(`${app.name} — ${status}`);
|
||||
tray.setContextMenu(
|
||||
Menu.buildFromTemplate([
|
||||
visible ?
|
||||
{ label: `Hide ${app.name}`, icon: this.icon("hide"), click: () => this.deps.hide() }
|
||||
: { label: `Open ${app.name}`, icon: this.icon("open"), click: () => this.deps.show() },
|
||||
{ type: "separator" },
|
||||
{ label: status, icon: this.icon(this.busy ? "busy" : "ready"), enabled: false },
|
||||
...(project ?
|
||||
[{ label: `Project: ${basename(project)}`, icon: this.icon("project"), enabled: false }]
|
||||
: []),
|
||||
{ type: "separator" },
|
||||
{ label: `Quit ${app.name}`, icon: this.icon("quit"), click: () => app.quit() },
|
||||
]),
|
||||
);
|
||||
|
||||
// Windows has no Dock to hint that closing the window did not quit; say
|
||||
// so once, the first time it goes away.
|
||||
if (process.platform === "win32" && this.wasVisible && !visible && !this.toldStillRunning) {
|
||||
this.toldStillRunning = true;
|
||||
tray.displayBalloon({
|
||||
iconType: "info",
|
||||
title: `${app.name} is still running`,
|
||||
content: "Agents can keep using it in the background. Open it again from here.",
|
||||
});
|
||||
}
|
||||
this.wasVisible = visible;
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
if (this.lingerTimer) clearTimeout(this.lingerTimer);
|
||||
nativeTheme.off("updated", this.onThemeUpdated);
|
||||
this.tray?.destroy();
|
||||
this.tray = null;
|
||||
}
|
||||
|
||||
private readonly onThemeUpdated = () => this.refresh();
|
||||
|
||||
/** The menu icon for the current theme, made once and reused. */
|
||||
private icon(name: MenuIcon): NativeImage {
|
||||
const dark = nativeTheme.shouldUseDarkColors;
|
||||
const key = `${name}:${dark}`;
|
||||
let icon = this.menuIcons.get(key);
|
||||
if (!icon) this.menuIcons.set(key, (icon = menuIcon(name, dark)));
|
||||
return icon;
|
||||
}
|
||||
|
||||
private updateBusy(): void {
|
||||
if (this.deps.active()) {
|
||||
if (this.lingerTimer) clearTimeout(this.lingerTimer);
|
||||
this.lingerTimer = null;
|
||||
this.busy = true;
|
||||
} else if (this.busy && !this.lingerTimer) {
|
||||
this.lingerTimer = setTimeout(() => {
|
||||
this.lingerTimer = null;
|
||||
this.busy = false;
|
||||
this.refresh();
|
||||
}, BUSY_LINGER);
|
||||
}
|
||||
}
|
||||
}
|
||||
7
apps/desktop/src/untyped-modules.d.ts
vendored
@ -13,10 +13,3 @@ declare module "@babel/preset-typescript" {
|
||||
const preset: unknown;
|
||||
export default preset;
|
||||
}
|
||||
|
||||
// The tray icons, bundled into main.js as bytes (`--loader:.png=binary`):
|
||||
// the packaged app ships dist/ and web/ only.
|
||||
declare module "*.png" {
|
||||
const bytes: Uint8Array;
|
||||
export default bytes;
|
||||
}
|
||||
|
||||
@ -1,145 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { EventEmitter } from "node:events";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const appEvents = new EventEmitter();
|
||||
const updaterEvents = new EventEmitter();
|
||||
const dock = { show: vi.fn(async () => { }), hide: vi.fn() };
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: { on: (event: string, listener: () => void) => appEvents.on(event, listener), dock, focus: () => { } },
|
||||
autoUpdater: { on: (event: string, listener: () => void) => updaterEvents.on(event, listener) },
|
||||
}));
|
||||
|
||||
const { WindowHost } = await import("./window-host");
|
||||
|
||||
/** Just enough of a BrowserWindow: visibility, close and destroy. */
|
||||
class FakeWindow extends EventEmitter {
|
||||
destroyed = false;
|
||||
isVisibleNow = false;
|
||||
isDestroyed = () => this.destroyed;
|
||||
isVisible = () => this.isVisibleNow;
|
||||
isFullScreen = () => false;
|
||||
isMinimized = () => false;
|
||||
show = () => void (this.isVisibleNow = true);
|
||||
hide = () => void (this.isVisibleNow = false);
|
||||
focus = () => { };
|
||||
restore = () => { };
|
||||
close(): void {
|
||||
const event = { defaultPrevented: false, preventDefault: () => void (event.defaultPrevented = true) };
|
||||
this.emit("close", event);
|
||||
if (!event.defaultPrevented) this.destroy();
|
||||
}
|
||||
destroy(): void {
|
||||
if (this.destroyed) return;
|
||||
this.destroyed = true;
|
||||
this.emit("closed");
|
||||
}
|
||||
}
|
||||
|
||||
const IDLE = 60_000;
|
||||
let created: FakeWindow[];
|
||||
let host: InstanceType<typeof WindowHost>;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
appEvents.removeAllListeners();
|
||||
updaterEvents.removeAllListeners();
|
||||
created = [];
|
||||
host = new WindowHost({
|
||||
create: () => {
|
||||
const window = new FakeWindow();
|
||||
created.push(window);
|
||||
// Painted right away, so `show` does not wait.
|
||||
queueMicrotask(() => window.emit("ready-to-show"));
|
||||
return window as never;
|
||||
},
|
||||
idleMs: IDLE,
|
||||
onChange: () => { },
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("WindowHost", () => {
|
||||
it("creates the window only when something needs it, and reuses it", () => {
|
||||
expect(host.current()).toBeNull();
|
||||
expect(host.acquire().fresh).toBe(true);
|
||||
expect(host.acquire().fresh).toBe(false);
|
||||
expect(created).toHaveLength(1);
|
||||
expect(host.visible()).toBe(false);
|
||||
});
|
||||
|
||||
it("destroys a hidden window once it has sat unused for the idle time", () => {
|
||||
host.acquire();
|
||||
vi.advanceTimersByTime(IDLE - 1);
|
||||
expect(host.current()).not.toBeNull();
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(host.current()).toBeNull();
|
||||
expect(host.acquire().fresh).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the window while a call holds it, and counts idle time from the release", () => {
|
||||
host.acquire();
|
||||
const release = host.hold();
|
||||
expect(host.active()).toBe(true);
|
||||
vi.advanceTimersByTime(IDLE * 2);
|
||||
expect(host.current()).not.toBeNull();
|
||||
release();
|
||||
release();
|
||||
expect(host.active()).toBe(false);
|
||||
vi.advanceTimersByTime(IDLE - 1);
|
||||
expect(host.current()).not.toBeNull();
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(host.current()).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the window while the renderer reports work of its own", () => {
|
||||
host.acquire();
|
||||
host.setBusy(true);
|
||||
vi.advanceTimersByTime(IDLE * 2);
|
||||
expect(host.current()).not.toBeNull();
|
||||
host.setBusy(false);
|
||||
vi.advanceTimersByTime(IDLE);
|
||||
expect(host.current()).toBeNull();
|
||||
});
|
||||
|
||||
it("never idles out a window the user has open, and gives the app a Dock icon while it is", async () => {
|
||||
await host.show();
|
||||
expect(host.visible()).toBe(true);
|
||||
expect(dock.show).toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(IDLE * 2);
|
||||
expect(host.current()).not.toBeNull();
|
||||
});
|
||||
|
||||
it("hides the window when the user closes it, and idles it out from there", async () => {
|
||||
await host.show();
|
||||
const window = created[0]!;
|
||||
window.close();
|
||||
expect(window.isDestroyed()).toBe(false);
|
||||
expect(host.visible()).toBe(false);
|
||||
expect(dock.hide).toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(IDLE);
|
||||
expect(window.isDestroyed()).toBe(true);
|
||||
});
|
||||
|
||||
it("lets the window close when the app quits", async () => {
|
||||
await host.show();
|
||||
appEvents.emit("before-quit");
|
||||
created[0]!.close();
|
||||
expect(created[0]!.isDestroyed()).toBe(true);
|
||||
expect(host.current()).toBeNull();
|
||||
});
|
||||
|
||||
it("lets the window close when an update quits the app to install", async () => {
|
||||
await host.show();
|
||||
updaterEvents.emit("before-quit-for-update");
|
||||
created[0]!.close();
|
||||
expect(created[0]!.isDestroyed()).toBe(true);
|
||||
});
|
||||
});
|
||||
@ -1,177 +0,0 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The main window's lifecycle. The app runs in the background while agents
|
||||
// use it — a tray icon, no Dock icon, no window — and the window, and with it
|
||||
// the renderer that answers most tools, only exists while something needs
|
||||
// it: a tool call, or the user. Hidden and unused for long enough, it is torn
|
||||
// down again, and the app is back to its main process alone.
|
||||
//
|
||||
// Everything that shows, hides or needs the window comes through here, so
|
||||
// the Dock icon (macOS) follows whether the window is showing, and closing
|
||||
// the window hides it rather than ending what the renderer is doing.
|
||||
|
||||
import { app, autoUpdater } from "electron";
|
||||
|
||||
import type { BrowserWindow } from "electron";
|
||||
|
||||
export type WindowHostDeps = {
|
||||
/** A new main window, not shown; loading starts right away. */
|
||||
create(): BrowserWindow;
|
||||
/** How long a hidden window may sit unused before it is destroyed. */
|
||||
idleMs: number;
|
||||
/** Whether the window is showing, or whether calls are running, changed. */
|
||||
onChange(): void;
|
||||
};
|
||||
|
||||
/** Longest a first show waits for the page to paint before showing it anyway. */
|
||||
const FIRST_PAINT_TIMEOUT = 5000;
|
||||
|
||||
export class WindowHost {
|
||||
private readonly deps: WindowHostDeps;
|
||||
private window: BrowserWindow | null = null;
|
||||
private painted: Promise<void> = Promise.resolve();
|
||||
// Whether the user should be seeing the window: set by `show`, cleared by
|
||||
// `hide`. Not `isVisible()`, which a minimize or ⌘H also clears — neither
|
||||
// of those is the user putting the window away, so neither lets it idle
|
||||
// out or takes the Dock icon.
|
||||
private shown = false;
|
||||
private holds = 0;
|
||||
private busy = false;
|
||||
private idleTimer: NodeJS.Timeout | null = null;
|
||||
private quitting = false;
|
||||
|
||||
constructor(deps: WindowHostDeps) {
|
||||
this.deps = deps;
|
||||
app.on("before-quit", () => {
|
||||
this.quitting = true;
|
||||
});
|
||||
// quitAndInstall closes the windows before `before-quit`; a close turned
|
||||
// into a hide there would leave the app running and the update unapplied.
|
||||
autoUpdater.on("before-quit-for-update", () => {
|
||||
this.quitting = true;
|
||||
});
|
||||
}
|
||||
|
||||
/** The window, if there is one. */
|
||||
current(): BrowserWindow | null {
|
||||
return this.window && !this.window.isDestroyed() ? this.window : null;
|
||||
}
|
||||
|
||||
/** Whether the window is out for the user (minimized counts). */
|
||||
visible(): boolean {
|
||||
return this.shown && this.current() !== null;
|
||||
}
|
||||
|
||||
/** Whether any call is holding the window. */
|
||||
active(): boolean {
|
||||
return this.holds > 0;
|
||||
}
|
||||
|
||||
/** The window, created hidden when there is none; `fresh` when this call created it. */
|
||||
acquire(): { window: BrowserWindow; fresh: boolean } {
|
||||
const existing = this.current();
|
||||
if (existing) return { window: existing, fresh: false };
|
||||
|
||||
const window = this.deps.create();
|
||||
this.window = window;
|
||||
this.painted = new Promise((resolve) => {
|
||||
window.once("ready-to-show", () => resolve());
|
||||
setTimeout(resolve, FIRST_PAINT_TIMEOUT);
|
||||
});
|
||||
|
||||
// Closing puts the window away; only quitting ends it (and idling out,
|
||||
// which destroys it without a `close`).
|
||||
window.on("close", (event) => {
|
||||
if (this.quitting) return;
|
||||
event.preventDefault();
|
||||
this.hide();
|
||||
});
|
||||
window.on("closed", () => {
|
||||
if (this.window !== window) return;
|
||||
this.window = null;
|
||||
this.shown = false;
|
||||
this.busy = false;
|
||||
this.clearIdle();
|
||||
this.deps.onChange();
|
||||
});
|
||||
|
||||
this.scheduleIdle();
|
||||
return { window, fresh: true };
|
||||
}
|
||||
|
||||
/** Shows and focuses the window, creating it when there is none. */
|
||||
async show(): Promise<void> {
|
||||
const { window } = this.acquire();
|
||||
this.shown = true;
|
||||
this.clearIdle();
|
||||
// Before the window: shown by an app without a Dock icon, it would not
|
||||
// come to the front.
|
||||
if (process.platform === "darwin") await app.dock?.show();
|
||||
await this.painted;
|
||||
if (window.isDestroyed()) return;
|
||||
if (window.isMinimized()) window.restore();
|
||||
window.show();
|
||||
window.focus();
|
||||
if (process.platform === "darwin") app.focus({ steal: true });
|
||||
this.deps.onChange();
|
||||
}
|
||||
|
||||
/** Puts the window away. It stays loaded until it idles out. */
|
||||
hide(): void {
|
||||
const window = this.current();
|
||||
if (!window) return;
|
||||
// Hiding a full-screen window leaves its empty Space behind.
|
||||
if (window.isFullScreen()) {
|
||||
window.once("leave-full-screen", () => this.hide());
|
||||
window.setFullScreen(false);
|
||||
return;
|
||||
}
|
||||
this.shown = false;
|
||||
window.hide();
|
||||
if (process.platform === "darwin") app.dock?.hide();
|
||||
this.scheduleIdle();
|
||||
this.deps.onChange();
|
||||
}
|
||||
|
||||
/** Keeps the window from idling out until the returned release is called. */
|
||||
hold(): () => void {
|
||||
this.holds++;
|
||||
this.clearIdle();
|
||||
if (this.holds === 1) this.deps.onChange();
|
||||
let released = false;
|
||||
return () => {
|
||||
if (released) return;
|
||||
released = true;
|
||||
this.holds--;
|
||||
this.scheduleIdle();
|
||||
if (this.holds === 0) this.deps.onChange();
|
||||
};
|
||||
}
|
||||
|
||||
/** Work the renderer started itself (an export from the UI) that must not be cut off. */
|
||||
setBusy(busy: boolean): void {
|
||||
this.busy = busy;
|
||||
if (busy) this.clearIdle();
|
||||
else this.scheduleIdle();
|
||||
}
|
||||
|
||||
private scheduleIdle(): void {
|
||||
this.clearIdle();
|
||||
if (!this.idle()) return;
|
||||
this.idleTimer = setTimeout(() => {
|
||||
this.idleTimer = null;
|
||||
if (this.idle()) this.current()?.destroy();
|
||||
}, this.deps.idleMs);
|
||||
}
|
||||
|
||||
private idle(): boolean {
|
||||
return this.current() !== null && !this.shown && this.holds === 0 && !this.busy;
|
||||
}
|
||||
|
||||
private clearIdle(): void {
|
||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||
this.idleTimer = null;
|
||||
}
|
||||
}
|
||||
@ -1,4 +1,8 @@
|
||||
VITE_SUPABASE_URL=https://mpvhvyxuqfcemfnwiaiq.supabase.co
|
||||
VITE_SUPABASE_ANON_KEY=sb_publishable_V-K9coUWXVy8dsZPGKDw-g_d1JzJf8u
|
||||
|
||||
VITE_UMAMI_WEBSITE_ID=e898e381-6ce3-4f5f-a485-8327ec9aa88b
|
||||
VITE_UMAMI_SCRIPT_URL=https://cloud.umami.is/script.js
|
||||
VITE_UMAMI_DOMAINS=diffusion.studio,app.diffusion.studio
|
||||
|
||||
VITE_API_URL=https://api.diffusion.studio
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@diffusionstudio/web",
|
||||
"private": true,
|
||||
"version": "0.216.0",
|
||||
"version": "0.205.0",
|
||||
"license": "MPL-2.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@ -14,7 +14,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@diffusionstudio/agent-chat": "*",
|
||||
"@diffusionstudio/api-contract": "^0.5.0",
|
||||
"@diffusionstudio/api-contract": "^0.1.0",
|
||||
"@diffusionstudio/assets": "*",
|
||||
"@diffusionstudio/dapi": "*",
|
||||
"@diffusionstudio/encoder": "*",
|
||||
@ -22,7 +22,6 @@
|
||||
"@diffusionstudio/koota-solid": "*",
|
||||
"@diffusionstudio/reconciler": "*",
|
||||
"@diffusionstudio/runtime": "*",
|
||||
"@diffusionstudio/sam2": "*",
|
||||
"@kobalte/core": "^0.13.11",
|
||||
"@sentry/solid": "^10.51.0",
|
||||
"@solid-primitives/keyboard": "^1.3.3",
|
||||
@ -30,8 +29,8 @@
|
||||
"@solid-primitives/resize-observer": "^2.1.3",
|
||||
"@solidjs/router": "^0.15.4",
|
||||
"@supabase/supabase-js": "^2.99.2",
|
||||
"@trpc/client": "^11.19.0",
|
||||
"@trpc/server": "^11.19.0",
|
||||
"@trpc/client": "^11.10.0",
|
||||
"@trpc/server": "^11.10.0",
|
||||
"animejs": "^4.4.1",
|
||||
"cmdk-solid": "^1.1.2",
|
||||
"colord": "^2.9.3",
|
||||
|
||||
@ -2,31 +2,28 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// Dropping files and folders onto a composer. Nothing is read, copied or
|
||||
// uploaded: an attachment is a path the agent reads where it is, so drops
|
||||
// only work where the shell can say where a file lives (the desktop app).
|
||||
// Shared by the home view and the chat composer.
|
||||
|
||||
import { Show, createSignal } from "solid-js";
|
||||
import { toast } from "somoto";
|
||||
|
||||
import { pickFiles } from "@diffusionstudio/assets";
|
||||
|
||||
import { Icon } from "@/components/ui/icon";
|
||||
import { RemoveButton } from "@/components/ui/remove-button";
|
||||
import { cx } from "@/lib/cva";
|
||||
|
||||
import { client, hasHost } from "./connection";
|
||||
|
||||
/**
|
||||
* A file or folder dropped onto a composer. Only what the tile and the
|
||||
* handoff need: the name to label it, the kind and extension to draw it, and
|
||||
* the path to send — null off the desktop, where the browser will not say
|
||||
* where a dropped file lives. An image picked, dropped or pasted also carries
|
||||
* an object URL for its thumbnail; one rebuilt from a path does not.
|
||||
* where a dropped file lives.
|
||||
*/
|
||||
export type Attachment = {
|
||||
key: string;
|
||||
name: string;
|
||||
kind: "file" | "folder";
|
||||
path: string | null;
|
||||
preview?: string;
|
||||
};
|
||||
|
||||
/** The paths worth sending: attachments the shell could locate. */
|
||||
@ -55,81 +52,19 @@ export function droppedAttachments(event: DragEvent): Attachment[] {
|
||||
const file = item.getAsFile();
|
||||
if (!file) continue;
|
||||
|
||||
result.push(fileAttachment(file, entry?.isDirectory ? "folder" : "file", entry?.name || file.name));
|
||||
const path = window.desktop?.getPathForFile(file) || null;
|
||||
const name = entry?.name || file.name;
|
||||
result.push({
|
||||
key: path ?? `${name}:${file.size}:${file.lastModified}`,
|
||||
name,
|
||||
kind: entry?.isDirectory ? "folder" : "file",
|
||||
path,
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/** A file picked or dropped without the entry API, which only a drop has. */
|
||||
function fileAttachment(file: File, kind: Attachment["kind"] = "file", name = file.name, path = window.desktop?.getPathForFile(file) || null): Attachment {
|
||||
const preview = kind === "file" && file.type.startsWith("image/") ? URL.createObjectURL(file) : undefined;
|
||||
return { key: path ?? `${name}:${file.size}:${file.lastModified}`, name, kind, path, ...(preview ? { preview } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The files on the clipboard. None when the paste is text: rich text from a
|
||||
* document app carries a picture of itself alongside, and that is not what
|
||||
* the user meant to paste.
|
||||
*/
|
||||
function pastedFiles(event: ClipboardEvent): File[] {
|
||||
const data = event.clipboardData;
|
||||
if (!data || data.types.includes("text/rtf")) return [];
|
||||
return Array.from(data.files);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pasted files as attachments. A file copied in the Finder has a path and is
|
||||
* sent as it is; a screenshot or an image copied from a page is only bytes,
|
||||
* so it is uploaded to the agent host, which may not share this disk, and
|
||||
* the path it was written to is what gets sent.
|
||||
*/
|
||||
async function pastedAttachments(files: File[]): Promise<Attachment[]> {
|
||||
return Promise.all(
|
||||
files.map(async (file) => {
|
||||
const path = window.desktop?.getPathForFile(file) || null;
|
||||
if (path) return file.type.startsWith("image/") ? fileAttachment(file, "file", file.name, path) : attachmentFromPath(path);
|
||||
if (!hasHost()) return fileAttachment(file);
|
||||
const saved = await client.request("attachments.upload", { name: file.name, data: await base64(file) });
|
||||
return fileAttachment(file, "file", file.name, saved.path);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** A file's bytes as base64, without the data URL's prefix. */
|
||||
function base64(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => {
|
||||
const url = reader.result as string;
|
||||
resolve(url.slice(url.indexOf(",") + 1));
|
||||
};
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* A paste handler for a composer: files go to `onPaste`, text is left to the
|
||||
* textarea. A paste that fails to save is a toast, not a lost image.
|
||||
*/
|
||||
export function createPasteHandler(onPaste: (pasted: Attachment[]) => void) {
|
||||
return (event: ClipboardEvent) => {
|
||||
const files = pastedFiles(event);
|
||||
if (files.length === 0) return;
|
||||
event.preventDefault();
|
||||
pastedAttachments(files).then(onPaste, (error: Error) =>
|
||||
toast.error("Could not paste the file", { description: error.message }),
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
/** Files chosen from the system picker, as attachments; folders can only be dropped. */
|
||||
export async function pickAttachments(): Promise<Attachment[]> {
|
||||
const files = await pickFiles({ accept: "" });
|
||||
return files.map((file) => fileAttachment(file));
|
||||
}
|
||||
|
||||
/** The same file dropped twice is one attachment, not two tiles. */
|
||||
export function mergeAttachments(current: Attachment[], dropped: Attachment[]): Attachment[] {
|
||||
const known = new Set(current.map((entry) => entry.key));
|
||||
@ -199,7 +134,7 @@ export function DropOverlay(props: { radius?: string }) {
|
||||
shape-rendering="crispEdges"
|
||||
/>
|
||||
</svg>
|
||||
<Icon name="attachment" class="text-muted-foreground" />
|
||||
<Icon name="attachment" class="size-6 text-muted-foreground" />
|
||||
<span class="text-xs font-450 text-muted-foreground">Drop files or folders here</span>
|
||||
</div>
|
||||
</div>
|
||||
@ -213,9 +148,9 @@ type AttachmentTileProps = {
|
||||
};
|
||||
|
||||
/**
|
||||
* One attached file or folder: the image itself when there is one to show,
|
||||
* else a grey square with a folder mark, or the file's type in the middle.
|
||||
* The name is in the tooltip and the remove button appears on hover, as it
|
||||
* One dropped file or folder: a grey square with a folder mark, or the file's
|
||||
* type in the middle. There is no thumbnail to show — nothing is loaded — so
|
||||
* the name is in the tooltip and the remove button appears on hover, as it
|
||||
* does on the generation composer's reference images.
|
||||
*/
|
||||
export function AttachmentTile(props: AttachmentTileProps) {
|
||||
@ -226,21 +161,14 @@ export function AttachmentTile(props: AttachmentTileProps) {
|
||||
>
|
||||
<div class="grid size-full place-items-center overflow-hidden rounded-lg bg-input text-muted-foreground">
|
||||
<Show
|
||||
when={props.attachment.preview}
|
||||
when={props.attachment.kind === "folder"}
|
||||
fallback={
|
||||
<Show
|
||||
when={props.attachment.kind === "folder"}
|
||||
fallback={
|
||||
<span class="max-w-9 truncate px-0.5 text-[9px] font-450 uppercase tracking-wide">
|
||||
{fileType(props.attachment.name)}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
<Icon name="navigation.folder" />
|
||||
</Show>
|
||||
<span class="max-w-9 truncate px-0.5 text-[9px] font-450 uppercase tracking-wide">
|
||||
{fileType(props.attachment.name)}
|
||||
</span>
|
||||
}
|
||||
>
|
||||
{(src) => <img src={src()} alt="" draggable={false} class="size-full object-cover" />}
|
||||
<Icon name="navigation.folder" class="size-6" />
|
||||
</Show>
|
||||
</div>
|
||||
<RemoveButton
|
||||
@ -256,7 +184,7 @@ export function AttachmentTile(props: AttachmentTileProps) {
|
||||
export function AttachmentChip(props: { path: string }) {
|
||||
const attachment = () => attachmentFromPath(props.path);
|
||||
return (
|
||||
<span class="inline-flex h-5 max-w-full items-center gap-0.5 rounded border border-border bg-transparent pl-0.5 pr-1.5 text-[11px] text-muted-foreground" title={props.path}>
|
||||
<span class="inline-flex h-5 max-w-full items-center gap-0.5 rounded bg-input pl-0.5 pr-1.5 text-[11px] text-muted-foreground" title={props.path}>
|
||||
<Icon name={attachment().kind === "folder" ? "navigation.folder" : "attachment"} class="size-4" />
|
||||
<span class="truncate">{attachment().name}</span>
|
||||
</span>
|
||||
|
||||
@ -136,8 +136,9 @@ export function ChatPanel() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div class="flex flex-1 min-h-0 flex-col">
|
||||
<div class="flex h-12 shrink-0 items-center border-y border-border px-4 [[data-platform=win32]_&]:border-t-0">
|
||||
<div class="flex h-full min-h-0 flex-col" data-right-sidebar>
|
||||
{/* The inspector's first section draws a top border under its header; the same hairline here keeps the tabs aligned. */}
|
||||
<div class="flex h-12 shrink-0 items-center border-b border-border px-4">
|
||||
<SidebarTabs />
|
||||
<HeaderActions
|
||||
projectId={project.id()}
|
||||
|
||||
@ -8,12 +8,11 @@
|
||||
|
||||
import { For, Show, createEffect } from "solid-js";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Icon } from "@/components/ui/icon";
|
||||
|
||||
import type { ModelRef } from "@diffusionstudio/agent-chat";
|
||||
|
||||
import { AttachmentTile, DropOverlay, createDropZone, createPasteHandler, mergeAttachments, pickAttachments, type Attachment } from "./attachments";
|
||||
import { AttachmentTile, DropOverlay, createDropZone, mergeAttachments, type Attachment } from "./attachments";
|
||||
import { ModelPicker } from "./model-picker";
|
||||
|
||||
const MAX_HEIGHT_PX = 160;
|
||||
@ -38,9 +37,7 @@ type ComposerProps = {
|
||||
export function Composer(props: ComposerProps) {
|
||||
let textarea: HTMLTextAreaElement | undefined;
|
||||
|
||||
const attach = (added: Attachment[]) => props.onAttachments(mergeAttachments(props.attachments, added));
|
||||
const drop = createDropZone(attach);
|
||||
const paste = createPasteHandler(attach);
|
||||
const drop = createDropZone((dropped) => props.onAttachments(mergeAttachments(props.attachments, dropped)));
|
||||
|
||||
const canSend = () => !props.running && !props.blocked && props.model !== null && (props.text.trim().length > 0 || props.attachments.length > 0);
|
||||
|
||||
@ -55,16 +52,6 @@ export function Composer(props: ComposerProps) {
|
||||
resize();
|
||||
});
|
||||
|
||||
// The panel mounts whenever the Chat tab comes up: land in the box, ready
|
||||
// to type. It may still be disabled while the host connects, and a disabled
|
||||
// box can't take focus — so focus it the first time it is enabled.
|
||||
let focused = false;
|
||||
createEffect(() => {
|
||||
if (focused || props.blocked !== null) return;
|
||||
focused = true;
|
||||
textarea?.focus();
|
||||
});
|
||||
|
||||
// Enter sends, shift+enter breaks the line — and the editor's shortcuts
|
||||
// have no business reading what is typed here. While a turn runs Enter
|
||||
// does nothing: there is no queue.
|
||||
@ -84,7 +71,6 @@ export function Composer(props: ComposerProps) {
|
||||
onDragEnter={drop.onDragEnter}
|
||||
onDragLeave={drop.onDragLeave}
|
||||
onDrop={drop.onDrop}
|
||||
onPaste={paste}
|
||||
>
|
||||
<Show when={props.attachments.length > 0}>
|
||||
{/* The remove buttons overhang the tiles' corners, and a scrolling
|
||||
@ -105,7 +91,6 @@ export function Composer(props: ComposerProps) {
|
||||
|
||||
<textarea
|
||||
ref={textarea}
|
||||
data-chat-composer
|
||||
value={props.text}
|
||||
onInput={(event) => props.onText(event.currentTarget.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
@ -114,48 +99,36 @@ export function Composer(props: ComposerProps) {
|
||||
placeholder={props.blocked ?? "Do anything"}
|
||||
disabled={props.blocked !== null}
|
||||
rows={1}
|
||||
class="max-h-40 min-h-7 w-full resize-none overflow-auto bg-transparent p-1 text-xs leading-5 text-foreground outline-none placeholder:text-muted-foreground selection:bg-selection selection:text-selection-foreground disabled:cursor-default"
|
||||
class="max-h-40 min-h-7 w-full resize-none overflow-auto bg-transparent p-1 text-[12px] leading-5 text-foreground outline-none placeholder:text-muted-foreground selection:bg-selection selection:text-selection-foreground disabled:cursor-default"
|
||||
/>
|
||||
|
||||
<div class="flex min-h-4 items-center justify-between gap-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-square"
|
||||
onClick={async () => attach(await pickAttachments())}
|
||||
aria-label="Add files"
|
||||
title="Add files"
|
||||
class="text-muted-foreground hover:bg-muted"
|
||||
>
|
||||
<Icon name="plus-add" />
|
||||
</Button>
|
||||
<div class="flex min-w-0 items-center gap-1.5">
|
||||
<ModelPicker value={props.model} onSelect={props.onModel} class="min-w-0" />
|
||||
<Show
|
||||
when={props.running}
|
||||
fallback={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => canSend() && props.onSend()}
|
||||
disabled={!canSend()}
|
||||
aria-label="Send"
|
||||
title={sendTitle()}
|
||||
class="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground transition-opacity hover:bg-primary-hover disabled:pointer-events-none disabled:opacity-40 focus-ring"
|
||||
>
|
||||
<Icon name="arrow-top" />
|
||||
</button>
|
||||
}
|
||||
>
|
||||
<ModelPicker value={props.model} onSelect={props.onModel} class="min-w-0" />
|
||||
<Show
|
||||
when={props.running}
|
||||
fallback={
|
||||
<button
|
||||
type="button"
|
||||
onClick={props.onStop}
|
||||
aria-label="Stop"
|
||||
title="Stop"
|
||||
class="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground hover:bg-primary-hover focus-ring"
|
||||
onClick={() => canSend() && props.onSend()}
|
||||
disabled={!canSend()}
|
||||
aria-label="Send"
|
||||
title={sendTitle()}
|
||||
class="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground transition-opacity hover:bg-primary-hover disabled:pointer-events-none disabled:opacity-40 focus-ring"
|
||||
>
|
||||
<Icon name="stop" />
|
||||
<Icon name="arrow-top" />
|
||||
</button>
|
||||
</Show>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={props.onStop}
|
||||
aria-label="Stop"
|
||||
title="Stop"
|
||||
class="grid size-7 shrink-0 place-items-center rounded-full bg-primary text-primary-foreground hover:bg-primary-hover focus-ring"
|
||||
>
|
||||
<Icon name="stop" />
|
||||
</button>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
<Show when={drop.dragging()}>
|
||||
|
||||
@ -16,11 +16,10 @@ type HeaderActionsProps = {
|
||||
onOpenChat(chatId: string): void;
|
||||
};
|
||||
|
||||
/** History (Chat history) and plus (New chat), at the right of the header. */
|
||||
/** Plus (New chat) and history (Chat history), at the right of the header. */
|
||||
export function HeaderActions(props: HeaderActionsProps) {
|
||||
return (
|
||||
<div class="ml-auto flex items-center gap-1 relative z-30" style="-webkit-app-region: no-drag;">
|
||||
<HistoryMenu projectId={props.projectId} chatId={props.chatId} onOpen={props.onOpenChat} />
|
||||
<Tooltip placement="bottom">
|
||||
<TooltipTrigger
|
||||
as={Button}
|
||||
@ -33,8 +32,9 @@ export function HeaderActions(props: HeaderActionsProps) {
|
||||
>
|
||||
<Icon name="plus-add" />
|
||||
</TooltipTrigger>
|
||||
<TooltipContent shortcut="⇧⌘L">New chat</TooltipContent>
|
||||
<TooltipContent>New chat</TooltipContent>
|
||||
</Tooltip>
|
||||
<HistoryMenu projectId={props.projectId} chatId={props.chatId} onOpen={props.onOpenChat} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@ -76,10 +76,10 @@ export function HistoryMenu(props: HistoryMenuProps) {
|
||||
{(chat) => (
|
||||
<DropdownMenuItem tone="neutral" class="group/row" onSelect={() => props.onOpen(chat.id)}>
|
||||
<Show when={chat.status === "running"}>
|
||||
<Icon name="spinner-loader" class="animate-spin -mr-1 shrink-0" />
|
||||
<Icon name="spinner-loader" class="animate-spin size-6 -mr-1 shrink-0" />
|
||||
</Show>
|
||||
<Show when={chat.status === "waiting"}>
|
||||
<Icon name="dot" class="-mr-1 shrink-0 text-primary" />
|
||||
<Icon name="dot" class="size-6 -mr-1 shrink-0 text-primary" />
|
||||
</Show>
|
||||
<span class="min-w-0 flex-1 truncate" title={chat.title}>
|
||||
{chat.title}
|
||||
@ -90,7 +90,7 @@ export function HistoryMenu(props: HistoryMenuProps) {
|
||||
</span>
|
||||
</Show>
|
||||
<Show when={chat.id === props.chatId}>
|
||||
<Icon name="confirm-check" class="-mr-1 shrink-0 group-hover/row:hidden" />
|
||||
<Icon name="confirm-check" class="size-6 -mr-1 shrink-0 group-hover/row:hidden" />
|
||||
</Show>
|
||||
<button
|
||||
type="button"
|
||||
@ -102,7 +102,7 @@ export function HistoryMenu(props: HistoryMenuProps) {
|
||||
>
|
||||
<Icon
|
||||
name="close-remove-small"
|
||||
class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-inherit!"
|
||||
class="absolute left-1/2 top-1/2 size-6 -translate-x-1/2 -translate-y-1/2 text-inherit!"
|
||||
/>
|
||||
</button>
|
||||
</DropdownMenuItem>
|
||||
|
||||
@ -3,14 +3,14 @@
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// The chat panel, and the few things the rest of the app touches: the
|
||||
// left sidebar's tabs and width, the model picker the home
|
||||
// right sidebar and its tabs, the sidebar width, the model picker the home
|
||||
// view shares, the home-view handoff, and the attachment helpers.
|
||||
|
||||
export { ChatPanel } from "./chat-panel";
|
||||
export { RightSidebar } from "./right-sidebar";
|
||||
export { SidebarTabs } from "./sidebar-tabs";
|
||||
export { ModelPicker, harnessIcon } from "./model-picker";
|
||||
export {
|
||||
leftSidebarWidth,
|
||||
rightSidebarWidth,
|
||||
sidebarTab,
|
||||
setSidebarTab,
|
||||
startChat,
|
||||
@ -18,7 +18,7 @@ export {
|
||||
storedModel,
|
||||
setStoredModel,
|
||||
ensureConnected,
|
||||
ASSETS_SIDEBAR_WIDTH,
|
||||
EDITOR_SIDEBAR_WIDTH,
|
||||
CHAT_SIDEBAR_WIDTH,
|
||||
} from "./store";
|
||||
export {
|
||||
@ -26,9 +26,7 @@ export {
|
||||
DropOverlay,
|
||||
attachmentPaths,
|
||||
createDropZone,
|
||||
createPasteHandler,
|
||||
droppedAttachments,
|
||||
mergeAttachments,
|
||||
pickAttachments,
|
||||
type Attachment,
|
||||
} from "./attachments";
|
||||
|
||||
@ -19,17 +19,13 @@ type Of<K extends Item["kind"]> = Extract<Item, { kind: K }>;
|
||||
|
||||
export function UserItem(props: { item: Of<"user"> }) {
|
||||
return (
|
||||
<div class="flex flex-col gap-1">
|
||||
<div class="rounded-md bg-muted px-2 py-1.5">
|
||||
<div class="whitespace-pre-wrap break-words text-[12px] leading-5 text-foreground">{props.item.text}</div>
|
||||
<Show when={props.item.attachments?.length}>
|
||||
<div class="flex flex-col items-end gap-1">
|
||||
<div class="mt-1 flex flex-wrap gap-1">
|
||||
<For each={props.item.attachments}>{(path) => <AttachmentChip path={path} />}</For>
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={props.item.text.trim()}>
|
||||
<div class="whitespace-pre-wrap break-words rounded-md bg-muted px-2 py-1.5 text-[12px] leading-5 text-foreground">
|
||||
{props.item.text}
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -55,7 +51,7 @@ export function ReasoningItem(props: { item: Of<"reasoning"> }) {
|
||||
aria-expanded={open()}
|
||||
onClick={() => expandable() && setOpen(!open())}
|
||||
>
|
||||
<Icon name={open() ? "chevron-down" : "chevron-right"} />
|
||||
<Icon name={open() ? "chevron-down" : "chevron-right"} class="size-6" />
|
||||
<span>Thinking</span>
|
||||
</button>
|
||||
<Show when={open()}>
|
||||
@ -80,13 +76,13 @@ export function ToolItem(props: { item: Of<"tool"> }) {
|
||||
onClick={() => expandable() && setOpen(!open())}
|
||||
>
|
||||
<Show when={props.item.status === "running"}>
|
||||
<Icon name="spinner-loader" class="shrink-0 animate-spin" />
|
||||
<Icon name="spinner-loader" class="size-6 shrink-0 animate-spin" />
|
||||
</Show>
|
||||
<Show when={props.item.status === "done"}>
|
||||
<Icon name="confirm-check" class="shrink-0" />
|
||||
<Icon name="confirm-check" class="size-6 shrink-0" />
|
||||
</Show>
|
||||
<Show when={props.item.status === "failed"}>
|
||||
<Icon name="close-remove-small" class="shrink-0 text-destructive" />
|
||||
<Icon name="close-remove-small" class="size-6 shrink-0 text-destructive" />
|
||||
</Show>
|
||||
<span class="shrink-0 font-450" classList={{ "agent-shimmer": props.item.status === "running" }}>
|
||||
{props.item.title}
|
||||
|
||||
@ -2,10 +2,9 @@
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// One dropdown for harness and model, two levels deep: Claude Code and
|
||||
// Codex first, each opening onto its models, fed by the host's probes. A
|
||||
// harness that is not ready is one disabled row that says why, never hidden,
|
||||
// so the picker also says what this works with.
|
||||
// One dropdown for harness and model: Claude Code's models, then Codex's,
|
||||
// fed by the host's probes. A harness that is not ready is one disabled row
|
||||
// that says why, never hidden, so the picker also says what this works with.
|
||||
|
||||
import { For, Show } from "solid-js";
|
||||
|
||||
@ -13,17 +12,13 @@ import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuGroupLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuItemDetail,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Icon } from "@/components/ui/icon";
|
||||
import { cx } from "@/lib/cva";
|
||||
|
||||
import type { HarnessId, HarnessInfo, ModelRef } from "@diffusionstudio/agent-chat";
|
||||
|
||||
@ -57,69 +52,66 @@ export function ModelPicker(props: ModelPickerProps) {
|
||||
const harnesses = () => chatState.harnesses;
|
||||
|
||||
return (
|
||||
<DropdownMenu placement="bottom-end" onOpenChange={(open) => open && refreshHarnesses()}>
|
||||
<DropdownMenu placement="bottom-start" onOpenChange={(open) => open && refreshHarnesses()}>
|
||||
<DropdownMenuTrigger
|
||||
as={Button}
|
||||
variant="ghost"
|
||||
as="button"
|
||||
type="button"
|
||||
aria-label="Choose the agent and model"
|
||||
class={cx("text-muted-foreground hover:bg-muted data-[expanded]:bg-muted", props.class)}
|
||||
class={`flex h-7 shrink-0 items-center rounded-md pl-0.5 pr-2 text-xs font-450 text-muted-foreground hover:bg-muted focus-ring ${props.class ?? ""}`}
|
||||
>
|
||||
<span class="grid size-6 shrink-0 place-items-center overflow-clip">
|
||||
<Icon name={harnessIcon(props.value?.harness)} />
|
||||
</span>
|
||||
<span class="max-w-40 truncate">{modelLabel(props.value)}</span>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuContent class="w-48">
|
||||
<DropdownMenuGroup>
|
||||
<Show when={harnesses().length === 0}>
|
||||
<DropdownMenuContent class="w-56">
|
||||
<Show when={harnesses().length === 0}>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem disabled>
|
||||
<span class="min-w-0 flex-1 truncate text-muted-foreground">
|
||||
{chatState.connection === "unavailable" ? "Chat runs in the desktop app" : "Connecting…"}
|
||||
</span>
|
||||
</DropdownMenuItem>
|
||||
</Show>
|
||||
<For each={harnesses()}>
|
||||
{(harness) => (
|
||||
<Show
|
||||
when={harness.status === "ready"}
|
||||
fallback={
|
||||
<DropdownMenuItem disabled>
|
||||
<Icon name={harnessIcon(harness.id)} />
|
||||
<span class="min-w-0 flex-1 truncate">{harness.label}</span>
|
||||
<DropdownMenuItemDetail class="truncate">{unavailableLabel(harness)}</DropdownMenuItemDetail>
|
||||
</DropdownMenuItem>
|
||||
}
|
||||
>
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>
|
||||
<span class="flex items-center gap-1">
|
||||
<Icon name={harnessIcon(harness.id)} />
|
||||
<span class="min-w-0 truncate">{harness.label}</span>
|
||||
</span>
|
||||
</DropdownMenuSubTrigger>
|
||||
<DropdownMenuPortal>
|
||||
<DropdownMenuSubContent class="w-48">
|
||||
<Show when={harness.detail}>
|
||||
{/* "Update Claude Code": the harness works, but is older than we test against. */}
|
||||
<p class="px-2 text-[10px] leading-3.5 text-muted-foreground">{harness.detail}</p>
|
||||
</Show>
|
||||
<DropdownMenuGroup>
|
||||
<For each={harness.models}>
|
||||
{(model) => (
|
||||
<DropdownMenuItem onSelect={() => props.onSelect({ harness: harness.id, model: model.id })}>
|
||||
<span class="min-w-0 flex-1 truncate">{model.label}</span>
|
||||
<Show when={props.value?.harness === harness.id && props.value?.model === model.id}>
|
||||
<Icon name="confirm-check" />
|
||||
</Show>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</For>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuSubContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenuSub>
|
||||
</DropdownMenuGroup>
|
||||
</Show>
|
||||
<For each={harnesses()}>
|
||||
{(harness, index) => (
|
||||
<>
|
||||
<Show when={index() > 0}>
|
||||
<DropdownMenuSeparator />
|
||||
</Show>
|
||||
)}
|
||||
</For>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuGroupLabel>{harness.label}</DropdownMenuGroupLabel>
|
||||
<Show when={harness.status === "ready" && harness.detail}>
|
||||
{/* "Update Claude Code": the harness works, but is older than we test against. */}
|
||||
<p class="px-2 pb-1 text-[10px] leading-3.5 text-muted-foreground">{harness.detail}</p>
|
||||
</Show>
|
||||
<Show
|
||||
when={harness.status === "ready"}
|
||||
fallback={
|
||||
<DropdownMenuItem disabled>
|
||||
<Icon name={harnessIcon(harness.id)} />
|
||||
<span class="min-w-0 flex-1 truncate text-muted-foreground">{unavailableLabel(harness)}</span>
|
||||
</DropdownMenuItem>
|
||||
}
|
||||
>
|
||||
<For each={harness.models}>
|
||||
{(model) => (
|
||||
<DropdownMenuItem onSelect={() => props.onSelect({ harness: harness.id, model: model.id })}>
|
||||
<Icon name={harnessIcon(harness.id)} />
|
||||
<span class="min-w-0 flex-1 truncate">{model.label}</span>
|
||||
<Show when={props.value?.harness === harness.id && props.value?.model === model.id}>
|
||||
<Icon name="confirm-check" class="size-6" />
|
||||
</Show>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</For>
|
||||
</Show>
|
||||
</DropdownMenuGroup>
|
||||
</>
|
||||
)}
|
||||
</For>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenuPortal>
|
||||
</DropdownMenu>
|
||||
|
||||
17
apps/web/src/agent-chat/right-sidebar.tsx
Normal file
@ -0,0 +1,17 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
import { Show, type JSX } from "solid-js";
|
||||
|
||||
import { ChatPanel } from "./chat-panel";
|
||||
import { sidebarTab } from "./store";
|
||||
|
||||
/** The right column: the editor's inspector, or the chat, by tab. */
|
||||
export function RightSidebar(props: { editor: () => JSX.Element }) {
|
||||
return (
|
||||
<Show when={sidebarTab() === "chat"} fallback={props.editor()}>
|
||||
<ChatPanel />
|
||||
</Show>
|
||||
);
|
||||
}
|
||||