Compare commits
339 Commits
jkl-implem
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 49be50aa99 | |||
| 0b8a3a505e | |||
|
|
af570c164a | ||
|
|
98ea0c986b | ||
|
|
68b633db3c | ||
|
|
a54e4152c3 | ||
|
|
5aeb75118a | ||
|
|
744dbcb6b7 | ||
|
|
b8869dd649 | ||
|
|
e2d070f968 | ||
|
|
783edc2197 | ||
|
|
075732f237 | ||
|
|
6a45d560d1 | ||
|
|
0491460e1a | ||
|
|
1ac2f5cc9a | ||
|
|
f3d3a08cc2 | ||
|
|
f29396e13a | ||
|
|
0cd29c91b8 | ||
|
|
efbc257512 | ||
|
|
78b0580c85 | ||
|
|
8107138490 | ||
|
|
d68a336199 | ||
|
|
7b3e1fc5e1 | ||
|
|
b01a79a9e1 | ||
|
|
a567775be1 | ||
|
|
53aa33ead9 | ||
|
|
c897d7b4d0 | ||
|
|
41ea0e26ab | ||
|
|
893eab6d02 | ||
|
|
66bed78f88 | ||
|
|
db9a6f668f | ||
|
|
5433beaebb | ||
|
|
250c4cc96f | ||
|
|
5681fd9bff | ||
|
|
9d8327b48d | ||
|
|
bbb2fad77a | ||
|
|
9b3983d32a | ||
|
|
6c6349a38f | ||
|
|
d3d2a0b468 | ||
|
|
3bf9f55067 | ||
|
|
c530e9ca09 | ||
|
|
56a8f09e53 | ||
|
|
748f31ac45 | ||
|
|
c413432d75 | ||
|
|
8d657e578e | ||
|
|
2609b28820 | ||
|
|
090669c999 | ||
|
|
9ccaac43ce | ||
|
|
e53775d581 | ||
|
|
82ebd30df7 | ||
|
|
b8f06155ed | ||
|
|
96d7242faa | ||
|
|
c95e6afc1d | ||
|
|
d8ca02ae02 | ||
|
|
ec84c73d62 | ||
|
|
9617d8adec | ||
|
|
c21f56a705 | ||
|
|
2a54059ea8 | ||
|
|
f964e5c798 | ||
|
|
29f214bc39 | ||
|
|
bb4ac3bdd8 | ||
|
|
17e09d1cc4 | ||
|
|
5d93ffee9c | ||
|
|
b9dcc6193e | ||
|
|
db5a4e90ad | ||
|
|
a3cd943478 | ||
|
|
5ac1c05eca | ||
|
|
7760cb569d | ||
|
|
fb8a924a7a | ||
|
|
e5a4024bdc | ||
|
|
ccf990a25b | ||
|
|
be7c406fb3 | ||
|
|
83e734a590 | ||
|
|
a5717bfb66 | ||
|
|
78fe83fbf8 | ||
|
|
bd11bc6b05 | ||
|
|
852b3d5138 | ||
|
|
47d38fb602 | ||
|
|
9a42b13865 | ||
|
|
58af16065d | ||
|
|
fb50341b0f | ||
|
|
c6a5c721e4 | ||
|
|
9bc577c771 | ||
|
|
450495c44b | ||
|
|
90ba4d0a2d | ||
|
|
8a1313b777 | ||
|
|
eeb0238603 | ||
|
|
d3260cb452 | ||
|
|
ed4a04fb44 | ||
|
|
d6c76e690d | ||
|
|
7a2eee7fe0 | ||
|
|
747a719148 | ||
|
|
daeb15f948 | ||
|
|
fc13c899f9 | ||
|
|
1fc4d16bf8 | ||
|
|
d5190170d6 | ||
|
|
e13b7f9edc | ||
|
|
2c736e5f4a | ||
|
|
bd3a67db17 | ||
|
|
3970904400 | ||
|
|
1e11b17ae7 | ||
|
|
b1aa6618b6 | ||
|
|
0e57cd2edc | ||
|
|
dd49464d56 | ||
|
|
5552978747 | ||
|
|
eaacc15fc8 | ||
|
|
3dbdb22953 | ||
|
|
83df6a2a4b | ||
|
|
21cb4d0e17 | ||
|
|
4e64fd8229 | ||
|
|
9f09a76ded | ||
|
|
09f227f49e | ||
|
|
5b7846382f | ||
|
|
81ab54fed1 | ||
|
|
d14c0f3c59 | ||
|
|
bdbe912409 | ||
|
|
acb7092faa | ||
|
|
83c38cc53a | ||
|
|
e836ffce14 | ||
|
|
38ecaef5c3 | ||
|
|
32ab74e482 | ||
|
|
3e376ca95f | ||
|
|
42ede69691 | ||
|
|
e6573a717d | ||
|
|
35f4cf6c26 | ||
|
|
55e1f1189f | ||
|
|
6e25123941 | ||
|
|
116eae23b8 | ||
|
|
e8c1bde745 | ||
|
|
4e232a3c5d | ||
|
|
9d09dbf0ca | ||
|
|
fe3f1d68e7 | ||
|
|
f10a6917f9 | ||
|
|
1f0476833b | ||
|
|
5c685e15b0 | ||
|
|
6ce93217bb | ||
|
|
e18ab84562 | ||
|
|
21589f4843 | ||
|
|
6a0ef3c188 | ||
|
|
d2e56157a4 | ||
|
|
73e578f47c | ||
|
|
8d9dfb690c | ||
|
|
62c1f1533d | ||
|
|
68b3095405 | ||
|
|
2c536d913d | ||
|
|
105f81de89 | ||
|
|
e5efb565c5 | ||
|
|
932c92d5f6 | ||
|
|
ecf97f8cc1 | ||
|
|
f4e7e7f54f | ||
|
|
75f0bfc8fc | ||
|
|
14feb5d4f7 | ||
|
|
56fb94104b | ||
|
|
8d3965fa9c | ||
|
|
e5b8971aac | ||
|
|
8616127c50 | ||
|
|
e3af57b136 | ||
|
|
9bde5fe6ef | ||
|
|
b83d6e4b80 | ||
|
|
6f14ce551a | ||
|
|
e4c4cdad4b | ||
|
|
d29d18b33c | ||
|
|
42753381ff | ||
|
|
77eee77313 | ||
|
|
8ff93b159b | ||
|
|
631d457373 | ||
|
|
1a8968a396 | ||
|
|
fefcde9df7 | ||
|
|
c99d8c2d3a | ||
|
|
c4fbd51f1d | ||
|
|
371841b253 | ||
|
|
f2d6f553b3 | ||
|
|
b59fdff188 | ||
|
|
ef3a20d4ba | ||
|
|
f1f6d87862 | ||
|
|
3a979f1660 | ||
|
|
ce9724df2c | ||
|
|
7215d92631 | ||
|
|
dd961f9ec2 | ||
|
|
d2f0ecb1de | ||
|
|
a69468fb5d | ||
|
|
f7f6ee02a3 | ||
|
|
f2a82581c9 | ||
|
|
11995532b6 | ||
|
|
fc63b73214 | ||
|
|
b06d5b21c7 | ||
|
|
f00276fd86 | ||
|
|
d302d4b938 | ||
|
|
5310ff0324 | ||
|
|
52e3a2a997 | ||
|
|
8c5529eacf | ||
|
|
22d32d9c22 | ||
|
|
a6e27ef3f2 | ||
|
|
77f7513960 | ||
|
|
794c5d8a83 | ||
|
|
ae33eabe52 | ||
|
|
a2ff21575a | ||
|
|
b195be7d01 | ||
|
|
67e783e5c8 | ||
|
|
16fe0cbec0 | ||
|
|
95b9531719 | ||
|
|
7e788582a4 | ||
|
|
b603f8b1da | ||
|
|
b528d8844c | ||
|
|
3f38c5eb60 | ||
|
|
caefe16d67 | ||
|
|
f40cadc07f | ||
|
|
5d1d023ea0 | ||
|
|
c7eb628ac0 | ||
|
|
4d5d9fc780 | ||
|
|
cde1cc1b53 | ||
|
|
b7866279fa | ||
|
|
88f74f8bfe | ||
|
|
37f6195ba0 | ||
|
|
e63f1c7a0f | ||
|
|
1882b539c9 | ||
|
|
70b2fa3ddf | ||
|
|
6d275f1a61 | ||
|
|
6c3901e543 | ||
|
|
6879ea773f | ||
|
|
666cdced1f | ||
|
|
2a3632aad5 | ||
|
|
2f05fbea8f | ||
|
|
7a9393d4e2 | ||
|
|
943912f247 | ||
|
|
1539fbc2e9 | ||
|
|
baeaad6b0a | ||
|
|
dc8f95eba7 | ||
|
|
bdf04a858e | ||
|
|
3beb859f31 | ||
|
|
39e65953ea | ||
|
|
3198fbade4 | ||
|
|
98251a55cd | ||
|
|
82bc3fd294 | ||
|
|
1324e365cf | ||
|
|
79765f55ad | ||
|
|
2e1ccb14f9 | ||
|
|
4d4d2ebe39 | ||
|
|
a34c00d46a | ||
|
|
7145e692be | ||
|
|
9c9768dee7 | ||
|
|
88b584f01b | ||
|
|
7904774023 | ||
|
|
e556af4bfd | ||
|
|
0d332f417c | ||
|
|
1bcbea6093 | ||
|
|
307a6a4a76 | ||
|
|
57c39834bb | ||
|
|
233cf487e5 | ||
|
|
0add88db09 | ||
|
|
1a10ee1583 | ||
|
|
e0ff7ecaea | ||
|
|
ac7f6aa247 | ||
|
|
a0f843fcac | ||
|
|
0afd65d33e | ||
|
|
0110f8c2d2 | ||
|
|
5166153c29 | ||
|
|
e7c71ba21e | ||
|
|
f1e6809c20 | ||
|
|
cb1116b23d | ||
|
|
6d2d52450e | ||
|
|
cb852b0ca5 | ||
|
|
f0040775d1 | ||
|
|
46cef22b26 | ||
|
|
c9e655856c | ||
|
|
b31741213f | ||
|
|
5529819672 | ||
|
|
5a229bd7a9 | ||
|
|
2593b928fe | ||
|
|
805affff28 | ||
|
|
53a9ecc7d9 | ||
|
|
9cfdc0d921 | ||
|
|
8691f37399 | ||
|
|
5d94b6d794 | ||
|
|
763ce7aa5c | ||
|
|
3cf1453968 | ||
|
|
7d9d2330a5 | ||
|
|
2874735936 | ||
|
|
f023adb4cd | ||
|
|
6bde47b9a1 | ||
|
|
df9d7d9f84 | ||
|
|
04f388ff33 | ||
|
|
223a39b87b | ||
|
|
c5bdfd88aa | ||
|
|
b36383c50f | ||
|
|
79a27580df | ||
|
|
9e8b209f04 | ||
|
|
d9d5f3a19c | ||
|
|
ba792a3295 | ||
|
|
f92a8339a4 | ||
|
|
8346fcdcb2 | ||
|
|
2367cb78da | ||
|
|
65d80a5b17 | ||
|
|
4acfb3e447 | ||
|
|
1bbe992345 | ||
|
|
28ad0372db | ||
|
|
d97d63baec | ||
|
|
a0ccde9e59 | ||
|
|
277d44e636 | ||
|
|
7a95fada7a | ||
|
|
c893dd6537 | ||
|
|
ae07aa4bc9 | ||
|
|
093aa671ac | ||
|
|
7372c40429 | ||
|
|
716d25c5a4 | ||
|
|
db2a3bd1f3 | ||
|
|
b13dec966a | ||
|
|
90cf84aa9b | ||
|
|
f0e66b3dd6 | ||
|
|
1532bf0e34 | ||
|
|
2e4c673989 | ||
|
|
8fbec32a57 | ||
|
|
50c8375a64 | ||
|
|
6eedc18141 | ||
|
|
2ca853ff70 | ||
|
|
2e7b8bf3e9 | ||
|
|
7ddd530eb2 | ||
|
|
9d36f71dec | ||
|
|
ad22093920 | ||
|
|
bdc10b212f | ||
|
|
f053820268 | ||
|
|
48c6672f51 | ||
|
|
ac10ecca25 | ||
|
|
ada3dcb3bc | ||
|
|
0e3a1e02f8 | ||
|
|
7f0e7d9d12 | ||
|
|
9fc1926acf | ||
|
|
b8ec5a39f7 | ||
|
|
312ce2e1b3 | ||
|
|
28135e68cc | ||
|
|
d5a298f004 | ||
|
|
5c0e109cd5 | ||
|
|
4d4cdda91e | ||
|
|
45d1ca0bc5 | ||
|
|
a7039fe8b2 | ||
|
|
4a652f589c | ||
|
|
059e1f6e76 | ||
|
|
905d649141 | ||
|
|
4d94b87881 |
37
.github/workflows/build-windows.yml
vendored
Normal file
@ -0,0 +1,37 @@
|
||||
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,8 +19,14 @@ 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}"
|
||||
curl -sfL -o app.dmg "https://github.com/diffusionstudio/editor/releases/download/${TAG}/Diffusion-Studio-arm64.dmg"
|
||||
# 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"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "sha256=$(shasum -a 256 app.dmg | cut -d' ' -f1)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
|
||||
72
.github/workflows/bump-winget.yml
vendored
Normal file
@ -0,0 +1,72 @@
|
||||
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,3 +54,106 @@ 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,4 +39,5 @@ out/
|
||||
# AI
|
||||
skills-lock.json
|
||||
.agents
|
||||
.claude
|
||||
.claude
|
||||
.gstack/
|
||||
|
||||
106
README.md
@ -4,10 +4,10 @@
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">The professional video editor built for agents</p>
|
||||
<p align="center">Turn your agent into a professional video editor</p>
|
||||
|
||||
<p align="center">
|
||||
<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://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://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,25 +49,16 @@ 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, it walks you through setting everything up:
|
||||
Download the desktop app for macOS (Apple Silicon) or Windows (x64), 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&logo=apple&logoColor=F8F8F8&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&labelColor=000000" alt="Download Diffusion Studio" /></a>
|
||||
|
||||
Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. `/editor` is the main skill you'll use. Ask for what you want in plain language. Behind it is `dapi`, the CLI that drives the app.
|
||||
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.
|
||||
|
||||
## Prompt examples
|
||||
|
||||
@ -75,11 +66,11 @@ Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. `/editor` is the ma
|
||||
<summary><b>Motion graphics</b></summary>
|
||||
|
||||
```text
|
||||
/editor 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.
|
||||
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.
|
||||
```
|
||||
|
||||
```text
|
||||
/editor Recreate the 3blue1brown animation from https://youtu.be/HEfHFsfGXjs, closely matching its visual style, pacing, framing, colors, labels, and transitions. Use the exact collision mathematics from Gregory Galperin's original paper, do not approximate the physics.
|
||||
Recreate the 3blue1brown animation from https://youtu.be/HEfHFsfGXjs, closely matching its visual style, pacing, framing, colors, labels, and transitions. Use the exact collision mathematics from Gregory Galperin's original paper, do not approximate the physics.
|
||||
```
|
||||
|
||||
</details>
|
||||
@ -88,11 +79,11 @@ Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. `/editor` is the ma
|
||||
<summary><b>Video editing</b></summary>
|
||||
|
||||
```text
|
||||
/editor edit the footage in /path/to/folder
|
||||
Edit the footage in /path/to/folder
|
||||
```
|
||||
|
||||
```text
|
||||
/editor turn this footage into a polished YouTube video. Add readable captions and an attention-grabbing graphic in the opening to give viewers a strong visual hook.
|
||||
Turn this footage into a polished YouTube video. Add readable captions and an attention-grabbing graphic in the opening to give viewers a strong visual hook.
|
||||
```
|
||||
|
||||
</details>
|
||||
@ -101,11 +92,11 @@ Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. `/editor` is the ma
|
||||
<summary><b>Clipping</b></summary>
|
||||
|
||||
```text
|
||||
/editor Can you pull the best 30-second moment from https://youtu.be/MtQ0qxyf-Ds and make a vertical version for social?
|
||||
Can you pull the best 30-second moment from https://youtu.be/MtQ0qxyf-Ds and make a vertical version for social?
|
||||
```
|
||||
|
||||
```text
|
||||
/editor Make a 15-second version of this launch video. https://x.com/claudeai/status/2045156267690213649
|
||||
Make a 15-second version of this launch video. https://x.com/claudeai/status/2045156267690213649
|
||||
```
|
||||
|
||||
</details>
|
||||
@ -114,11 +105,11 @@ Use with Claude Code, Codex, Cursor, Copilot, or Gemini CLI. `/editor` is the ma
|
||||
<summary><b>Video understanding and reasoning</b></summary>
|
||||
|
||||
```text
|
||||
/watch In three bullets, explain what starts the conflict. Include timestamps. https://youtu.be/aqz-KE-bpKQ
|
||||
In three bullets, explain what starts the conflict. Include timestamps. https://youtu.be/aqz-KE-bpKQ
|
||||
```
|
||||
|
||||
```text
|
||||
/watch Name three recurring locations and give one visual cue that distinguishes each. https://youtu.be/dQw4w9WgXcQ
|
||||
Name three recurring locations and give one visual cue that distinguishes each. https://youtu.be/dQw4w9WgXcQ
|
||||
```
|
||||
|
||||
</details>
|
||||
@ -131,9 +122,17 @@ 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: `dapi open <dir>` once, 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 (`diffusion 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.
|
||||
|
||||
@ -141,10 +140,6 @@ 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 },
|
||||
@ -155,7 +150,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={motion} start={0} end={5} width={1920} height={1080} />
|
||||
<video src="footage/city.mp4" start={0} end={5} width={1920} height={1080} />
|
||||
<For each={TITLES}>
|
||||
{(t) => (
|
||||
<text
|
||||
@ -182,38 +177,38 @@ Everything a mount produces stays a first-class editor node, so a person can pic
|
||||
|
||||
## Seeing and hearing the media
|
||||
|
||||
Cutting footage requires understanding it. The CLI ships the inspection tools an agent needs to work with media it cannot watch:
|
||||
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
|
||||
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
|
||||
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
|
||||
```
|
||||
|
||||
Each command is the MCP tool of the same name: `diffusion grab` is `grab`, `--per-sheet` is `perSheet`.
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `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 fetch` | Download a video from yt/tt/ig |
|
||||
| `dapi whoami` | The authenticated account |
|
||||
| `dapi report` | Report a bug in the CLI or the app: diagnostics bundled, filed as a GitHub issue via `gh` |
|
||||
| `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` |
|
||||
|
||||
Conventions throughout: single results are one JSON value, collections are JSON Lines, errors go to stderr with exit code `1`. Everything is built to be piped, grepped, and driven by a program.
|
||||
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
|
||||
|
||||
- [CLI reference](reference/README.md): every command, its options, and its output
|
||||
- [JSX reference](reference/jsx/README.md): the composition markup with elements, timing, paints, generative assets, and captions
|
||||
- [Examples](examples/README.md): runnable compositions, from basic scenes and generative assets to three.js and raw WebGPU
|
||||
- [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
|
||||
|
||||
## Repository layout
|
||||
|
||||
@ -221,10 +216,10 @@ Conventions throughout: single results are one JSON value, collections are JSON
|
||||
| --- | --- | --- |
|
||||
| `apps/web` | `@diffusionstudio/web` | The editor UI (Solid + Vite) |
|
||||
| `apps/desktop` | `@diffusionstudio/desktop` | Electron shell hosting the editor |
|
||||
| `apps/cli` | `@diffusionstudio/cli` | The `dapi` CLI |
|
||||
| `apps/cli` | `@diffusionstudio/cli` | The `diffusion` CLI (`dapi` alias): 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, types, and generated assets (`generate.*`) |
|
||||
| `packages/jsx` | `@diffusionstudio/jsx` | The authoring API: element vocabulary and types |
|
||||
| `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` |
|
||||
@ -243,19 +238,18 @@ cp apps/web/.env.example apps/web/.env # required: the app won't run without i
|
||||
npm run dev
|
||||
```
|
||||
|
||||
To put `dapi` on your PATH (macOS/Homebrew layout; adjust the link target for other setups), link it once:
|
||||
To put `diffusion` (and its `dapi` alias) on your PATH, link it once (`unlink` undoes it):
|
||||
|
||||
```sh
|
||||
npm run symlink:create --workspace=@diffusionstudio/cli
|
||||
npm run link --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,35 +1,27 @@
|
||||
{
|
||||
"name": "@diffusionstudio/cli",
|
||||
"private": true,
|
||||
"version": "0.204.2",
|
||||
"version": "0.216.0",
|
||||
"license": "MPL-2.0",
|
||||
"bin": {
|
||||
"diffusion": "./dist/index.js",
|
||||
"dapi": "./dist/index.js"
|
||||
},
|
||||
"exports": {
|
||||
"./protocol": "./src/protocol.ts",
|
||||
"./channels": "./src/cli-channels.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "esbuild src/index.ts --bundle --platform=node --format=cjs --external:esbuild --external:@babel/core --external:@babel/preset-typescript --external:babel-preset-solid --external:bufferutil --external:utf-8-validate --outfile=dist/index.js && chmod +x dist/index.js",
|
||||
"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)\"",
|
||||
"check": "tsc --noEmit",
|
||||
"symlink:remove": "rm -f /opt/homebrew/bin/dapi",
|
||||
"symlink:create": "npm run build && ln -sf \"$PWD/dist/index.js\" /opt/homebrew/bin/dapi"
|
||||
"link": "npm run build && node scripts/dev-link.mjs",
|
||||
"unlink": "node scripts/dev-link.mjs --remove"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.29.7",
|
||||
"@trpc/client": "^11.18.0",
|
||||
"@trpc/server": "^11.18.0",
|
||||
"@babel/preset-typescript": "^7.27.1",
|
||||
"babel-preset-solid": "^1.9.12",
|
||||
"@diffusionstudio/dapi": "*",
|
||||
"@modelcontextprotocol/sdk": "^1.30.0",
|
||||
"commander": "^14.0.3",
|
||||
"esbuild": "^0.28.1",
|
||||
"ws": "^8.18.3"
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@types/node": "^24.10.1",
|
||||
"@types/ws": "^8.18.1",
|
||||
"esbuild": "^0.28.1",
|
||||
"typescript": "~5.9.3"
|
||||
}
|
||||
}
|
||||
|
||||
119
apps/cli/scripts/dev-link.mjs
Normal file
@ -0,0 +1,119 @@
|
||||
/* 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;
|
||||
}
|
||||
@ -1,194 +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/. */
|
||||
|
||||
// Wire-level channel for the CLI handshake. Each CLI command hosts a
|
||||
// short-lived WebSocket server; main's only job is to relay the connect
|
||||
// info to the renderer, which then dials the CLI directly. Main never sees
|
||||
// request payloads.
|
||||
export const CLI_WIRE = {
|
||||
CONNECT: "cli:connect",
|
||||
} as const;
|
||||
|
||||
// Sent by the CLI to main over the unix socket, relayed verbatim to the
|
||||
// renderer. The token guards the loopback WebSocket server against other
|
||||
// local processes racing to connect first.
|
||||
export type CliHandshake = { port: number; token: string };
|
||||
|
||||
export type CliHandshakeReply = { ok: true } | { ok: false; error: string };
|
||||
|
||||
// One tRPC request/reply pair per WebSocket connection. `path` is the
|
||||
// dot-joined procedure path in the renderer's router (e.g. "media.frame");
|
||||
// procedure inputs and outputs are typed end-to-end via the AppRouter type,
|
||||
// so the wire envelope stays untyped.
|
||||
export type CliRequest = {
|
||||
path: string;
|
||||
input: unknown;
|
||||
};
|
||||
|
||||
export type CliReply =
|
||||
| { ok: true; data: unknown }
|
||||
| { ok: false; error: string };
|
||||
|
||||
export type AssetRef = { path: string };
|
||||
|
||||
export type MediaProbeRequest = AssetRef;
|
||||
|
||||
export type FrameQuality = "small" | "medium" | "large" | "fullres";
|
||||
export type MediaFrameRequest = AssetRef & {
|
||||
times?: number[];
|
||||
count?: number;
|
||||
start?: number;
|
||||
end?: number;
|
||||
quality?: FrameQuality;
|
||||
auto?: boolean;
|
||||
combine?: boolean;
|
||||
perSheet?: number;
|
||||
};
|
||||
|
||||
/** Beyond this the cells get too small to be worth the tokens; use `filmstrip`. */
|
||||
export const MAX_FRAMES_PER_SHEET = 12;
|
||||
|
||||
/**
|
||||
* One written image: a single frame stamped with its timecode, or a contact
|
||||
* sheet stamped with the span it covers (`0f-08s10f`).
|
||||
*/
|
||||
export type TimecodedImage = { timecode: string; base64: string };
|
||||
|
||||
export type MediaFrameResult = TimecodedImage[];
|
||||
|
||||
export type CaptureRequest = {
|
||||
id: string;
|
||||
frames?: number[];
|
||||
combine?: boolean;
|
||||
perSheet?: number;
|
||||
};
|
||||
|
||||
export type CaptureResult = TimecodedImage[];
|
||||
|
||||
export type MediaTranscribeRequest = AssetRef;
|
||||
export type TranscriptWord = { text: string; start: number; end: number };
|
||||
export type TranscriptSegment = { text: string; words: TranscriptWord[] };
|
||||
export type MediaTranscribeResult = { segments: TranscriptSegment[] };
|
||||
|
||||
export type MediaFilmstripRequest = AssetRef & { start?: number; end?: number; scale?: number };
|
||||
export type MediaFilmstripResult = { base64: string };
|
||||
|
||||
export type MediaWaveformRequest = AssetRef & { start?: number; end?: number; scale?: number };
|
||||
export type MediaWaveformResult = {
|
||||
base64: string;
|
||||
silences: Array<{ start: number; end: number }>;
|
||||
};
|
||||
|
||||
export type MediaListenRequest = AssetRef & { prompt?: string; start?: number; end?: number; stripVideo?: boolean };
|
||||
export type MediaListenResult = { result?: string; start?: number; end?: number };
|
||||
|
||||
export type CheckRequest = { id: string };
|
||||
|
||||
export type CheckIssueCode =
|
||||
| "black-frames"
|
||||
| "no-visuals"
|
||||
| "never-visible"
|
||||
| "zero-duration"
|
||||
| "transparent"
|
||||
| "source-error";
|
||||
|
||||
/**
|
||||
* One structural finding. `ranges` (where present) are seconds relative to
|
||||
* the checked node's start — the same clock `capture --time` uses.
|
||||
*/
|
||||
export type CheckIssue = {
|
||||
code: CheckIssueCode;
|
||||
severity: "error" | "warning";
|
||||
message: string;
|
||||
/** Source stamp of the offending node; absent when the issue is about the subtree as a whole. */
|
||||
node?: string;
|
||||
ranges?: Array<{ start: number; end: number }>;
|
||||
};
|
||||
|
||||
export type CheckResult = {
|
||||
stats: {
|
||||
/** Nodes in the subtree, the checked node included. */
|
||||
nodes: number;
|
||||
byKind: Record<string, number>;
|
||||
/** Deepest nesting level below the checked node (0 = no children). */
|
||||
depth: number;
|
||||
/** Seconds the checked node plays (its workarea, when one is set). */
|
||||
duration: number;
|
||||
};
|
||||
issues: CheckIssue[];
|
||||
};
|
||||
|
||||
export type ExportFormat = "mp4" | "webm" | "ogg" | "mov";
|
||||
|
||||
// The settings shape mirrors the scene's `diffusion.export.<id>` entry in the
|
||||
// project's package.json (see the web app's engine/project-config), spelled
|
||||
// out here so the wire seam stays dependency-free. Codecs are strings on the
|
||||
// wire; the app validates them against what the encoder accepts.
|
||||
export type ExportVideoSettings = {
|
||||
enabled?: boolean;
|
||||
codec?: string;
|
||||
bitrate?: number;
|
||||
fps?: number;
|
||||
resolution?: number;
|
||||
};
|
||||
|
||||
export type ExportAudioSettings = {
|
||||
enabled?: boolean;
|
||||
codec?: string;
|
||||
sampleRate?: number;
|
||||
bitrate?: number;
|
||||
};
|
||||
|
||||
export type ExportSettings = {
|
||||
format?: ExportFormat;
|
||||
video?: ExportVideoSettings;
|
||||
audio?: ExportAudioSettings;
|
||||
};
|
||||
|
||||
/**
|
||||
* `path` is the absolute output file, whose extension picks the container;
|
||||
* omitted, the app writes `exports/<id>.<format>` in the project folder.
|
||||
* Everything else — codecs, bitrates, resolution — is read from the scene's
|
||||
* export entry in the project's package.json.
|
||||
*/
|
||||
export type ExportRequest = { id: string; path?: string };
|
||||
|
||||
/**
|
||||
* `config` echoes the settings the export was made with — the package.json
|
||||
* entry (or the defaults), with the container the extension resolved to — so
|
||||
* a caller sees what its config edit actually did. `width`/`height` are the
|
||||
* encoded pixel size (0×0 for an audio-only export); `duration` is seconds.
|
||||
*/
|
||||
export type ExportResult = {
|
||||
path: string;
|
||||
width: number;
|
||||
height: number;
|
||||
duration: number;
|
||||
size: number;
|
||||
config: ExportSettings;
|
||||
};
|
||||
|
||||
export type GeneratedAsset = { id: string; name: string; type: string };
|
||||
|
||||
export type ModelsRequest = { type?: "image" | "video" | "audio" };
|
||||
|
||||
export type ModelInfo = {
|
||||
type: "image" | "video" | "audio";
|
||||
id: string;
|
||||
name: string;
|
||||
durations?: string[];
|
||||
aspectRatios?: string[];
|
||||
features?: Array<"start-frame" | "end-frame" | "audio">;
|
||||
};
|
||||
|
||||
export type VoiceInfo = { id: string; label: string; description: string };
|
||||
|
||||
export type ScreenshotResult = { base64: string; width: number; height: number };
|
||||
|
||||
export type LogLevel = "debug" | "info" | "warning" | "error";
|
||||
|
||||
export type LogEntry = { ts: number; level: LogLevel; message: string; source: string };
|
||||
|
||||
export type LogsRequest = { tail?: number; level?: LogLevel };
|
||||
|
||||
@ -2,166 +2,133 @@
|
||||
* 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 { connect } from "node:net";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { WebSocketServer } from "ws";
|
||||
import { createTRPCClient, TRPCClientError } from "@trpc/client";
|
||||
import type { TRPCLink } from "@trpc/client";
|
||||
import { observable } from "@trpc/server/observable";
|
||||
import { SOCKET_PATH } from "./protocol";
|
||||
import type { CliHandshake, CliHandshakeReply, CliReply, CliRequest } from "./protocol";
|
||||
import type { AppRouter } from "../../web/src/context/dapi";
|
||||
import { execFile, spawn } 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";
|
||||
import { version } from "../../../package.json";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 60000;
|
||||
export const GENERATE_TIMEOUT_MS = 600000;
|
||||
export const EXPORT_TIMEOUT_MS = 3600000;
|
||||
import type { ToolInput, ToolName, ToolOutput } from "@diffusionstudio/dapi";
|
||||
|
||||
// Asks the app (via the unix socket) to have the renderer dial our WebSocket
|
||||
// server. Main replies once the connect info has been delivered, so a
|
||||
// rejection here means the app is down or the renderer never became ready.
|
||||
function requestConnection(handshake: CliHandshake, timeoutMs: number): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock = connect(SOCKET_PATH);
|
||||
let buf = "";
|
||||
let settled = false;
|
||||
const settle = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
sock.destroy();
|
||||
fn();
|
||||
};
|
||||
export const APP_NAME = "Diffusion Studio";
|
||||
|
||||
sock.setEncoding("utf8");
|
||||
sock.setTimeout(timeoutMs, () =>
|
||||
settle(() => reject(new Error("Timed out waiting for the app to accept the connection"))),
|
||||
);
|
||||
sock.on("connect", () => sock.end(JSON.stringify(handshake)));
|
||||
sock.on("data", (chunk) => {
|
||||
buf += chunk;
|
||||
});
|
||||
sock.on("end", () => {
|
||||
let reply: CliHandshakeReply;
|
||||
try {
|
||||
reply = JSON.parse(buf) as CliHandshakeReply;
|
||||
} catch (e) {
|
||||
settle(() => reject(e instanceof Error ? e : new Error(String(e))));
|
||||
return;
|
||||
}
|
||||
if (reply.ok) settle(resolve);
|
||||
else settle(() => reject(new Error(reply.error)));
|
||||
});
|
||||
sock.on("error", (err) => settle(() => reject(err)));
|
||||
});
|
||||
}
|
||||
|
||||
async function transport(request: CliRequest, timeoutMs: number): Promise<unknown> {
|
||||
const token = randomBytes(16).toString("hex");
|
||||
// Frame batches and other base64 replies can exceed ws's 100 MiB default,
|
||||
// so disable the payload cap; the server only lives for one request.
|
||||
const wss = new WebSocketServer({ host: "127.0.0.1", port: 0, maxPayload: 0 });
|
||||
// Renders, media analysis and file transfers 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,
|
||||
};
|
||||
|
||||
/**
|
||||
* Calls one tool in the running app over an MCP session on its HTTP
|
||||
* endpoint — the same URL agents register. Typed by the catalog: the input is
|
||||
* what the tool's schema accepts, the output its structured content. One
|
||||
* session per call; a command makes one or two, and the process exits when
|
||||
* it settles.
|
||||
*/
|
||||
export async function call<N extends ToolName>(name: N, input: ToolInput<N>): Promise<ToolOutput<N>> {
|
||||
const client = await connect();
|
||||
try {
|
||||
const reply = await new Promise<CliReply>((resolve, reject) => {
|
||||
let settled = false;
|
||||
const timer = setTimeout(() => {
|
||||
settle(() => reject(new Error("Timed out waiting for response")));
|
||||
}, timeoutMs);
|
||||
const settle = (fn: () => void) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
fn();
|
||||
};
|
||||
|
||||
wss.on("error", (err) => settle(() => reject(err)));
|
||||
wss.on("connection", (ws, req) => {
|
||||
const url = new URL(req.url ?? "/", "ws://127.0.0.1");
|
||||
if (url.searchParams.get("token") !== token) {
|
||||
ws.terminate();
|
||||
return;
|
||||
}
|
||||
ws.on("message", (raw) => {
|
||||
try {
|
||||
const parsed = JSON.parse(raw.toString()) as CliReply;
|
||||
settle(() => resolve(parsed));
|
||||
} catch (e) {
|
||||
settle(() => reject(e instanceof Error ? e : new Error(String(e))));
|
||||
}
|
||||
});
|
||||
ws.on("close", () =>
|
||||
settle(() => reject(new Error("App disconnected before replying"))),
|
||||
);
|
||||
ws.on("error", (err) => settle(() => reject(err)));
|
||||
ws.send(JSON.stringify(request));
|
||||
});
|
||||
|
||||
wss.once("listening", () => {
|
||||
const { port } = wss.address() as AddressInfo;
|
||||
requestConnection({ port, token }, timeoutMs).catch((err) =>
|
||||
settle(() => reject(err instanceof Error ? err : new Error(String(err)))),
|
||||
);
|
||||
});
|
||||
const result = await client.callTool({ name, arguments: input as Record<string, unknown> }, undefined, {
|
||||
timeout: TIMEOUTS[name] ?? 60_000,
|
||||
});
|
||||
|
||||
if (reply.ok) return reply.data;
|
||||
throw new Error(reply.error);
|
||||
if (result.isError) {
|
||||
const text = (result.content as Array<{ type: string; text?: string }>)
|
||||
.filter((block) => block.type === "text")
|
||||
.map((block) => block.text)
|
||||
.join("\n");
|
||||
throw new Error(text || `${name} failed`);
|
||||
}
|
||||
return result.structuredContent as ToolOutput<N>;
|
||||
} finally {
|
||||
// Tear down explicitly so no lingering handles keep the Node event loop
|
||||
// alive past `console.log(result)` and block the CLI from exiting.
|
||||
for (const client of wss.clients) client.terminate();
|
||||
wss.close();
|
||||
await client.close().catch(() => { });
|
||||
}
|
||||
}
|
||||
|
||||
// Terminating link: each operation runs over its own short-lived WebSocket
|
||||
// server that the renderer dials in to. Long-running procedures pass
|
||||
// { context: { timeoutMs } } at the call site.
|
||||
const cliLink: TRPCLink<AppRouter> =
|
||||
() =>
|
||||
({ op }) =>
|
||||
observable((observer) => {
|
||||
const timeoutMs =
|
||||
typeof op.context.timeoutMs === "number" ? op.context.timeoutMs : DEFAULT_TIMEOUT_MS;
|
||||
transport({ path: op.path, input: op.input }, timeoutMs)
|
||||
.then((data) => {
|
||||
observer.next({ result: { data } });
|
||||
observer.complete();
|
||||
})
|
||||
.catch((err) => observer.error(TRPCClientError.from(err as Error)));
|
||||
// No cancellation: the CLI process exits when the command settles.
|
||||
return () => {};
|
||||
});
|
||||
|
||||
export const editor = createTRPCClient<AppRouter>({ links: [cliLink] });
|
||||
|
||||
// Transport failures surface as TRPCClientError wrapping the socket error;
|
||||
// unwrap to reach errno codes like ENOENT/ECONNREFUSED.
|
||||
export function errnoCode(e: unknown): string | undefined {
|
||||
if (!(e instanceof TRPCClientError)) return undefined;
|
||||
return (e.cause as NodeJS.ErrnoException | undefined)?.code;
|
||||
/** Liveness: a round-trip through the app's MCP server. */
|
||||
export async function ping(): Promise<void> {
|
||||
const client = await connect();
|
||||
try {
|
||||
await client.ping();
|
||||
} finally {
|
||||
await client.close().catch(() => { });
|
||||
}
|
||||
}
|
||||
|
||||
// Bridges the cold-start gap after launching the app. Main only delivers the
|
||||
// handshake once the renderer has finished loading, and `ping` is answered
|
||||
// by the always-mounted app router, so a single round-trip proves the app is
|
||||
// fully up. The retry loop only handles the brief window before the handshake
|
||||
// socket itself binds (ENOENT/ECONNREFUSED).
|
||||
export async function waitForCliSocket(timeoutMs = 30000): Promise<void> {
|
||||
// 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 });
|
||||
await client.connect(new StreamableHTTPClientTransport(new URL(MCP_URL)));
|
||||
return client;
|
||||
}
|
||||
|
||||
/**
|
||||
* Nothing is listening on the app's port. Node's fetch reports that as a
|
||||
* `fetch failed` TypeError whose cause carries the errno, so the chain of
|
||||
* causes is searched.
|
||||
*/
|
||||
export function isAppDown(e: unknown): boolean {
|
||||
for (let error = e, depth = 0; error && depth < 5; error = (error as { cause?: unknown }).cause, depth++) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "ECONNREFUSED" || code === "ECONNRESET") return true;
|
||||
}
|
||||
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> {
|
||||
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.
|
||||
*/
|
||||
export async function waitForApp(timeoutMs = 30000): Promise<void> {
|
||||
const start = Date.now();
|
||||
let lastError: unknown = null;
|
||||
while (Date.now() - start < timeoutMs) {
|
||||
try {
|
||||
await editor.ping.query();
|
||||
return;
|
||||
return await ping();
|
||||
} catch (e) {
|
||||
if (!isAppDown(e)) throw e;
|
||||
lastError = e;
|
||||
const code = errnoCode(e);
|
||||
if (code !== "ENOENT" && code !== "ECONNREFUSED") throw e;
|
||||
await new Promise((r) => setTimeout(r, 200));
|
||||
}
|
||||
}
|
||||
throw lastError instanceof Error
|
||||
? lastError
|
||||
: new Error("Timed out waiting for the app to start");
|
||||
const detail = lastError instanceof Error ? ` (${lastError.message})` : "";
|
||||
throw new Error(`${APP_NAME} did not answer within ${Math.round(timeoutMs / 1000)}s of launching${detail}`);
|
||||
}
|
||||
|
||||
@ -1,16 +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 { platform, tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
// One socket / named pipe per host. On macOS tmpdir is per-user; on Linux /tmp
|
||||
// is global but the socket file's owner-only mode 0600 keeps it isolated.
|
||||
//
|
||||
// Kept separate from cli-channels so the renderer can import the channel
|
||||
// registry and envelope types without pulling in node:os / node:path.
|
||||
export const SOCKET_PATH =
|
||||
platform() === "win32"
|
||||
? "\\\\.\\pipe\\diffusion-studio"
|
||||
: join(tmpdir(), "diffusion-studio.sock");
|
||||
@ -1,103 +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 { spawnSync } from "node:child_process";
|
||||
import { platform } from "node:os";
|
||||
|
||||
export type FontVariant = {
|
||||
weight: string;
|
||||
style: "normal" | "italic";
|
||||
source: string;
|
||||
};
|
||||
|
||||
export type FontFamily = {
|
||||
family: string;
|
||||
variants: FontVariant[];
|
||||
};
|
||||
|
||||
// JXA script that walks every registered font family via NSFontManager and
|
||||
// emits each variant's CSS-style weight, italic flag, and CSS `local()` source.
|
||||
// Embedded inline so the CLI binary is self-contained — 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);
|
||||
}
|
||||
`;
|
||||
|
||||
export type ListLocalFontsOptions = {
|
||||
familyPattern?: string;
|
||||
weights?: string[];
|
||||
style?: "normal" | "italic";
|
||||
limit?: number;
|
||||
};
|
||||
|
||||
export function listLocalFonts(options: ListLocalFontsOptions = {}): FontFamily[] {
|
||||
if (platform() !== "darwin") {
|
||||
throw new Error("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.");
|
||||
}
|
||||
|
||||
const all = JSON.parse(result.stdout.trim()) as FontFamily[];
|
||||
const pattern = options.familyPattern?.toLowerCase();
|
||||
const weights = options.weights && options.weights.length > 0 ? new Set(options.weights) : null;
|
||||
const { style, limit } = options;
|
||||
|
||||
const out: FontFamily[] = [];
|
||||
for (const family of all) {
|
||||
if (pattern && !family.family.toLowerCase().includes(pattern)) continue;
|
||||
const variants = family.variants.filter((v) => {
|
||||
if (weights && !weights.has(v.weight)) return false;
|
||||
if (style && v.style !== style) return false;
|
||||
return true;
|
||||
});
|
||||
if (variants.length === 0) continue;
|
||||
out.push({ family: family.family, variants });
|
||||
if (limit !== undefined && out.length >= limit) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
49
apps/cli/src/mcp-proxy.ts
Normal file
@ -0,0 +1,49 @@
|
||||
/* 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/. */
|
||||
|
||||
// `diffusion 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;
|
||||
// anything for a human goes to stderr.
|
||||
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { MCP_URL } from "@diffusionstudio/dapi";
|
||||
import { APP_NAME, isAppDown, launchApp, ping, waitForApp } from "./cli-client";
|
||||
|
||||
import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
|
||||
|
||||
export async function runProxy(): Promise<void> {
|
||||
try {
|
||||
await ping();
|
||||
} catch (e) {
|
||||
if (!isAppDown(e)) throw e;
|
||||
// Launching is macOS's job; elsewhere the user starts the app by hand.
|
||||
if (!(await launchApp(true))) {
|
||||
throw new Error(`${APP_NAME} is not running. Launch the app first, then retry.`);
|
||||
}
|
||||
await waitForApp();
|
||||
}
|
||||
|
||||
const upstream = new StreamableHTTPClientTransport(new URL(MCP_URL));
|
||||
const stdio = new StdioServerTransport();
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
console.error(`[diffusion 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}`);
|
||||
// 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.
|
||||
stdio.onclose = () => void upstream.close().finally(() => process.exit(0));
|
||||
|
||||
await upstream.start();
|
||||
await stdio.start();
|
||||
}
|
||||
@ -1,11 +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/. */
|
||||
|
||||
// Public wire protocol consumed by both the CLI binary and any host that
|
||||
// embeds the CLI socket server (the Diffusion Studio desktop app). Importing
|
||||
// from `@diffusionstudio/cli/protocol` is the OSS-friendly seam: this module has no
|
||||
// dependency on proprietary code, so the package stays extractable into its
|
||||
// own repo.
|
||||
export * from "./cli-channels";
|
||||
export * from "./cli-socket-path";
|
||||
15
apps/cli/src/untyped-modules.d.ts
vendored
@ -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/. */
|
||||
|
||||
// Babel presets ship no type declarations; they are only ever passed opaquely
|
||||
// into @babel/core's `presets` option.
|
||||
declare module "babel-preset-solid" {
|
||||
const preset: unknown;
|
||||
export default preset;
|
||||
}
|
||||
|
||||
declare module "@babel/preset-typescript" {
|
||||
const preset: unknown;
|
||||
export default preset;
|
||||
}
|
||||
@ -1,74 +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 { spawn, spawnSync } from "node:child_process";
|
||||
|
||||
// Resolve the binary once. YT_DLP_PATH mirrors DIFFUSION_APP_PATH: an escape
|
||||
// hatch for pinned or non-PATH installs.
|
||||
const BIN = process.env.YT_DLP_PATH ?? "yt-dlp";
|
||||
|
||||
// Fails with an actionable message before any download is attempted. ENOENT is
|
||||
// the "not installed" case; a non-zero status means the binary is present but
|
||||
// broken.
|
||||
function assertInstalled(): void {
|
||||
const probe = spawnSync(BIN, ["--version"], { encoding: "utf8" });
|
||||
if (probe.error) {
|
||||
if ((probe.error as NodeJS.ErrnoException).code === "ENOENT") {
|
||||
throw new Error(
|
||||
`yt-dlp not found. Install it (brew install yt-dlp, or pipx install yt-dlp) ` +
|
||||
`or set YT_DLP_PATH to its location.`,
|
||||
);
|
||||
}
|
||||
throw new Error(probe.error.message);
|
||||
}
|
||||
if (probe.status !== 0) {
|
||||
throw new Error(probe.stderr?.trim() || "yt-dlp is present but not runnable.");
|
||||
}
|
||||
}
|
||||
|
||||
export type FetchOptions = {
|
||||
output?: string;
|
||||
format?: string;
|
||||
audio?: boolean;
|
||||
raw?: string[];
|
||||
};
|
||||
|
||||
// Downloads the URL and resolves to the final file path(s) on disk. yt-dlp's
|
||||
// own `after_move:filepath` reports what actually landed (post extraction /
|
||||
// rename), so we never guess the name. --quiet silences stdout chatter while
|
||||
// --progress forces the progress bar to stderr, keeping stdout to just the
|
||||
// paths we capture.
|
||||
export function fetchVideo(url: string, opts: FetchOptions = {}): Promise<string[]> {
|
||||
assertInstalled();
|
||||
|
||||
const args = ["--quiet", "--no-warnings", "--progress", "--print", "after_move:filepath"];
|
||||
if (opts.output) args.push("-o", opts.output);
|
||||
if (opts.format) {
|
||||
args.push("-f", opts.format);
|
||||
} else if (!opts.audio) {
|
||||
// Default to mp4: prefer mp4/m4a streams, then remux the merged result so
|
||||
// the landed file is a .mp4 even when only WebM/mkv sources were available.
|
||||
// An explicit -f or --audio opts out.
|
||||
args.push("-f", "bv*[ext=mp4]+ba[ext=m4a]/b[ext=mp4]/bv*+ba/b", "--merge-output-format", "mp4");
|
||||
}
|
||||
if (opts.audio) args.push("-x");
|
||||
if (opts.raw?.length) args.push(...opts.raw);
|
||||
args.push(url);
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
// stdout: resolved paths (captured); stderr: live progress (inherited).
|
||||
const child = spawn(BIN, args, { stdio: ["ignore", "pipe", "inherit"] });
|
||||
let out = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => (out += chunk));
|
||||
child.on("error", reject);
|
||||
child.on("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve(out.split("\n").map((line) => line.trim()).filter(Boolean));
|
||||
} else {
|
||||
reject(new Error(`yt-dlp exited with code ${code}.`));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
@ -2,40 +2,9 @@
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.tsbuildinfo",
|
||||
// The AppRouter type import in cli-client.ts pulls renderer sources into
|
||||
// this program, so the web app's compiler settings (DOM, solid JSX, vite
|
||||
// types, aliases) apply here on top of the node ones.
|
||||
"useDefineForClassFields": true,
|
||||
"erasableSyntaxOnly": false,
|
||||
"lib": [
|
||||
"es2024",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"types": [
|
||||
"node",
|
||||
"vite-plugin-solid-svg/types-component-solid",
|
||||
"vite/client",
|
||||
"@types/audioworklet",
|
||||
"@types/wicg-file-system-access",
|
||||
"@webgpu/types"
|
||||
],
|
||||
"resolveJsonModule": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"jsx": "preserve",
|
||||
"jsxImportSource": "solid-js",
|
||||
"baseUrl": "./",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"../web/src/*"
|
||||
],
|
||||
"@desktop/*": [
|
||||
"../desktop/src/*"
|
||||
]
|
||||
}
|
||||
"lib": ["es2024"],
|
||||
"types": ["node"],
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": [
|
||||
"src",
|
||||
"../web/src/vite-env.d.ts"
|
||||
]
|
||||
"include": ["src"]
|
||||
}
|
||||
|
||||
2
apps/desktop/.gitignore
vendored
@ -2,5 +2,5 @@ dist
|
||||
web
|
||||
out
|
||||
cli
|
||||
runtime
|
||||
docs
|
||||
skills
|
||||
|
||||
46
apps/desktop/assets/app.manifest
Normal file
@ -0,0 +1,46 @@
|
||||
<?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>
|
||||
BIN
apps/desktop/assets/icon-win.png
Normal file
|
After Width: | Height: | Size: 336 KiB |
BIN
apps/desktop/assets/icon.ico
Normal file
|
After Width: | Height: | Size: 180 KiB |
BIN
apps/desktop/assets/install-spinner.gif
Normal file
|
After Width: | Height: | Size: 37 KiB |
BIN
apps/desktop/assets/tray/busyTemplate.png
Normal file
|
After Width: | Height: | Size: 420 B |
BIN
apps/desktop/assets/tray/busyTemplate@2x.png
Normal file
|
After Width: | Height: | Size: 755 B |
BIN
apps/desktop/assets/tray/idleTemplate.png
Normal file
|
After Width: | Height: | Size: 369 B |
BIN
apps/desktop/assets/tray/idleTemplate@2x.png
Normal file
|
After Width: | Height: | Size: 635 B |
BIN
apps/desktop/assets/tray/menu/busy.png
Normal file
|
After Width: | Height: | Size: 231 B |
3
apps/desktop/assets/tray/menu/busy.svg
Normal file
@ -0,0 +1,3 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 338 B |
BIN
apps/desktop/assets/tray/menu/busy@2x.png
Normal file
|
After Width: | Height: | Size: 397 B |
BIN
apps/desktop/assets/tray/menu/hide.png
Normal file
|
After Width: | Height: | Size: 320 B |
4
apps/desktop/assets/tray/menu/hide.svg
Normal file
@ -0,0 +1,4 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 461 B |
BIN
apps/desktop/assets/tray/menu/hide@2x.png
Normal file
|
After Width: | Height: | Size: 615 B |
BIN
apps/desktop/assets/tray/menu/open.png
Normal file
|
After Width: | Height: | Size: 231 B |
3
apps/desktop/assets/tray/menu/open.svg
Normal file
@ -0,0 +1,3 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 230 B |
BIN
apps/desktop/assets/tray/menu/open@2x.png
Normal file
|
After Width: | Height: | Size: 403 B |
BIN
apps/desktop/assets/tray/menu/project.png
Normal file
|
After Width: | Height: | Size: 258 B |
3
apps/desktop/assets/tray/menu/project.svg
Normal file
@ -0,0 +1,3 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 288 B |
BIN
apps/desktop/assets/tray/menu/project@2x.png
Normal file
|
After Width: | Height: | Size: 353 B |
BIN
apps/desktop/assets/tray/menu/quit.png
Normal file
|
After Width: | Height: | Size: 310 B |
3
apps/desktop/assets/tray/menu/quit.svg
Normal file
@ -0,0 +1,3 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 226 B |
BIN
apps/desktop/assets/tray/menu/quit@2x.png
Normal file
|
After Width: | Height: | Size: 574 B |
BIN
apps/desktop/assets/tray/menu/ready.png
Normal file
|
After Width: | Height: | Size: 343 B |
3
apps/desktop/assets/tray/menu/ready.svg
Normal file
@ -0,0 +1,3 @@
|
||||
<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>
|
||||
|
After Width: | Height: | Size: 231 B |
BIN
apps/desktop/assets/tray/menu/ready@2x.png
Normal file
|
After Width: | Height: | Size: 741 B |
BIN
apps/desktop/assets/tray/win.png
Normal file
|
After Width: | Height: | Size: 999 B |
BIN
apps/desktop/assets/tray/win@2x.png
Normal file
|
After Width: | Height: | Size: 1.9 KiB |
@ -2,15 +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/. */
|
||||
|
||||
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 { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
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';
|
||||
|
||||
const { version } = JSON.parse(readFileSync(join(__dirname, '..', '..', 'package.json'), 'utf8'));
|
||||
|
||||
|
||||
const sign = windowsSign();
|
||||
|
||||
const config: ForgeConfig = {
|
||||
packagerConfig: {
|
||||
name: 'Diffusion Studio',
|
||||
@ -18,6 +26,12 @@ 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) =>
|
||||
@ -27,21 +41,35 @@ const config: ForgeConfig = {
|
||||
!path.startsWith('/dist/') &&
|
||||
path !== '/web' &&
|
||||
!path.startsWith('/web/'),
|
||||
// Staged by scripts/stage-{cli,docs,skills}.mjs; end up at
|
||||
// Contents/Resources/{cli,docs,skills}.
|
||||
extraResource: ['./cli', './docs', './skills'],
|
||||
// Staged by scripts/stage-{cli,runtime,docs}.mjs; end up at
|
||||
// Contents/Resources/{cli,runtime,docs}.
|
||||
extraResource: ['./cli', './runtime', './docs'],
|
||||
osxSign: process.env.SKIP_SIGN ? undefined : {},
|
||||
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',
|
||||
@ -64,6 +92,55 @@ 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.204.2",
|
||||
"version": "0.216.0",
|
||||
"license": "MPL-2.0",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@ -10,35 +10,44 @@
|
||||
"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 --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 --loader:.png=binary --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:native",
|
||||
"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",
|
||||
"stage:cli": "npm --prefix ../cli run build && node scripts/stage-cli.mjs",
|
||||
"stage:runtime": "node scripts/stage-runtime.mjs",
|
||||
"stage:docs": "node scripts/stage-docs.mjs",
|
||||
"stage:skills": "node scripts/stage-skills.mjs",
|
||||
"check": "tsc --noEmit",
|
||||
"dev": "npm run build && electron-forge start",
|
||||
"package": "npm run build && npm run build:web && npm run stage:cli && npm run stage:docs && npm run stage:skills && electron-forge package",
|
||||
"make": "npm run build && npm run build:web && npm run stage:cli && npm run stage:docs && npm run stage:skills && electron-forge make",
|
||||
"publish": "npm run build && npm run build:web && npm run stage:cli && npm run stage:docs && npm run stage:skills && electron-forge publish",
|
||||
"make:icns": "sh scripts/make-icns.sh"
|
||||
"package": "npm run build && npm run build:web && npm run stage:cli && npm run stage:runtime && npm run stage:docs && electron-forge package",
|
||||
"make": "npm run build && npm run build:web && npm run stage:cli && npm run stage:runtime && npm run stage:docs && electron-forge make",
|
||||
"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"
|
||||
},
|
||||
"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",
|
||||
"@types/node": "^24.10.1",
|
||||
"electron": "^43.1.1",
|
||||
"typescript": "~5.9.3"
|
||||
"typescript": "~5.9.3",
|
||||
"vitest": "^4.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.29.7",
|
||||
"@babel/preset-typescript": "^7.27.1",
|
||||
"@diffusionstudio/cli": "*",
|
||||
"@diffusionstudio/agent-chat": "*",
|
||||
"@diffusionstudio/dapi": "*",
|
||||
"@diffusionstudio/jsx": "*",
|
||||
"@modelcontextprotocol/sdk": "^1.30.0",
|
||||
"babel-preset-solid": "^1.9.12",
|
||||
"esbuild": "^0.28.1",
|
||||
"nanoid": "^6.0.1",
|
||||
|
||||
@ -4,12 +4,19 @@
|
||||
|
||||
// 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)
|
||||
// cli/node_modules deps the bundle keeps external (esbuild, babel)
|
||||
// cli/bin/dapi shell wrapper, the file that gets linked into PATH
|
||||
// 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.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmodSync, cpSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { chmodSync, cpSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@ -17,40 +24,16 @@ const desktopDir = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const cliDir = join(desktopDir, "..", "cli");
|
||||
const stageDir = join(desktopDir, "cli");
|
||||
|
||||
// Must match the --external list in the apps/cli build script, minus ws's
|
||||
// optional native addons (bufferutil, utf-8-validate): those are external
|
||||
// only so the bundle doesn't choke on them, and ws falls back to its JS
|
||||
// implementations when they are absent.
|
||||
const EXTERNALS = ["esbuild", "@babel/core", "@babel/preset-typescript", "babel-preset-solid"];
|
||||
|
||||
const cliPkg = JSON.parse(readFileSync(join(cliDir, "package.json"), "utf8"));
|
||||
|
||||
rmSync(stageDir, { recursive: true, force: true });
|
||||
mkdirSync(join(stageDir, "bin"), { recursive: true });
|
||||
|
||||
cpSync(join(cliDir, "dist", "index.js"), join(stageDir, "dapi.js"));
|
||||
|
||||
writeFileSync(
|
||||
join(stageDir, "package.json"),
|
||||
JSON.stringify(
|
||||
{
|
||||
name: "dapi-runtime",
|
||||
private: true,
|
||||
dependencies: Object.fromEntries(EXTERNALS.map((name) => [name, cliPkg.dependencies[name]])),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
|
||||
execFileSync("npm", ["install", "--omit=dev", "--no-audit", "--no-fund", "--no-package-lock"], {
|
||||
cwd: stageDir,
|
||||
stdio: "inherit",
|
||||
});
|
||||
|
||||
// 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
|
||||
@ -64,27 +47,23 @@ 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" "$@"
|
||||
`;
|
||||
writeFileSync(join(stageDir, "bin", "dapi"), wrapper);
|
||||
chmodSync(join(stageDir, "bin", "dapi"), 0o755);
|
||||
|
||||
// Mach-O files inside Resources are not reached by the app-bundle signing
|
||||
// pass, and notarization rejects unsigned executables; sign them here.
|
||||
if (process.platform === "darwin" && !process.env.SKIP_SIGN) {
|
||||
const identities = execFileSync("security", ["find-identity", "-v", "-p", "codesigning"], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
const identity = identities.match(/"(Developer ID Application: [^"]+)"/)?.[1];
|
||||
if (identity) {
|
||||
const esbuildDir = join(stageDir, "node_modules", "@esbuild");
|
||||
for (const pkg of readdirSync(esbuildDir)) {
|
||||
const bin = join(esbuildDir, pkg, "bin", "esbuild");
|
||||
execFileSync("codesign", ["--force", "--options", "runtime", "--timestamp", "--sign", identity, bin], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn("stage-cli: no Developer ID identity found, leaving esbuild binary unsigned");
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
console.log(`stage-cli: staged dapi at ${stageDir}`);
|
||||
|
||||
@ -2,12 +2,11 @@
|
||||
* 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/. */
|
||||
|
||||
// Stages the authoring docs into apps/desktop/docs so electron-forge can ship
|
||||
// them as an app resource (Contents/Resources/docs). The layout mirrors the
|
||||
// repo — reference/ beside examples/ — because the relative links between the
|
||||
// pages assume it. scaffold() copies the tree into each project's
|
||||
// .diffusion/docs, so what an agent reads in a project is exactly what was
|
||||
// staged here (see src/projects.ts).
|
||||
// Stages the docs into apps/desktop/docs so electron-forge can ship them as
|
||||
// an app resource (Contents/Resources/docs). The app's MCP server sends
|
||||
// INSTRUCTIONS.md on connect along with this folder's path; agents read the
|
||||
// rest as plain files. The tree is copied as it is in the repo, because the
|
||||
// relative links between the pages assume that layout.
|
||||
|
||||
import { cpSync, mkdirSync, rmSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
@ -19,8 +18,9 @@ const stageDir = join(desktopDir, "docs");
|
||||
|
||||
rmSync(stageDir, { recursive: true, force: true });
|
||||
mkdirSync(stageDir, { recursive: true });
|
||||
for (const name of ["reference", "examples"]) {
|
||||
cpSync(join(repoRoot, name), join(stageDir, name), { recursive: true });
|
||||
}
|
||||
cpSync(join(repoRoot, "docs"), stageDir, {
|
||||
recursive: true,
|
||||
filter: (path) => !path.endsWith(".DS_Store") && !path.endsWith(".gitkeep"),
|
||||
});
|
||||
|
||||
console.log(`stage-docs: staged docs at ${stageDir}`);
|
||||
console.log(`stage-docs: staged the docs at ${stageDir}`);
|
||||
|
||||
85
apps/desktop/scripts/stage-runtime.mjs
Normal file
@ -0,0 +1,85 @@
|
||||
/* 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/. */
|
||||
|
||||
// Stages the main process's external dependencies into apps/desktop/runtime
|
||||
// so electron-forge can ship them as an app resource (Contents/Resources/
|
||||
// runtime). A packaged app has no node_modules of its own: everything else
|
||||
// is bundled into dist/main.js, but esbuild (native binary) and the babel
|
||||
// toolchain stay external and are loaded from here at run time (see `load`
|
||||
// in src/projects.ts). The staged layout:
|
||||
// runtime/package.json the externals, pinned to the workspace's versions
|
||||
// runtime/node_modules a fresh `npm install --omit=dev` of them
|
||||
//
|
||||
// The list of externals is read from the build:main script so that it cannot
|
||||
// drift from what the bundle actually leaves unresolved.
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
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");
|
||||
const require = createRequire(join(desktopDir, "package.json"));
|
||||
|
||||
const pkg = JSON.parse(readFileSync(join(desktopDir, "package.json"), "utf8"));
|
||||
const externals = [...pkg.scripts["build:main"].matchAll(/--external:(\S+)/g)]
|
||||
.map((match) => match[1])
|
||||
// Electron is provided by the host binary, not installed.
|
||||
.filter((name) => name !== "electron");
|
||||
|
||||
// Pin what the workspace has installed (and was tested against), not the
|
||||
// ranges in package.json.
|
||||
const dependencies = Object.fromEntries(
|
||||
externals.map((name) => [name, require(`${name}/package.json`).version]),
|
||||
);
|
||||
|
||||
rmSync(stageDir, { recursive: true, force: true });
|
||||
mkdirSync(stageDir, { recursive: true });
|
||||
|
||||
writeFileSync(
|
||||
join(stageDir, "package.json"),
|
||||
JSON.stringify({ name: "desktop-runtime", private: true, dependencies }, null, 2),
|
||||
);
|
||||
|
||||
npm(["install", "--omit=dev", "--no-audit", "--no-fund", "--no-package-lock"], { cwd: stageDir });
|
||||
|
||||
// Mach-O files inside Resources are not reached by the app-bundle signing
|
||||
// pass, and notarization rejects unsigned executables; sign them here.
|
||||
// esbuild's postinstall hard-links the native binary over its bin/esbuild
|
||||
// shim, so the same executable can sit in two places.
|
||||
const MACHO_MAGIC = new Set([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe, 0xcafebabe]);
|
||||
function isMachO(path) {
|
||||
const fd = openSync(path, "r");
|
||||
try {
|
||||
const header = Buffer.alloc(4);
|
||||
return readSync(fd, header, 0, 4, 0) === 4 && MACHO_MAGIC.has(header.readUInt32BE(0));
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
}
|
||||
|
||||
const esbuildDir = join(stageDir, "node_modules", "@esbuild");
|
||||
const binaries = [
|
||||
join(stageDir, "node_modules", "esbuild", "bin", "esbuild"),
|
||||
...(existsSync(esbuildDir) ? readdirSync(esbuildDir).map((name) => join(esbuildDir, name, "bin", "esbuild")) : []),
|
||||
].filter((path) => existsSync(path) && isMachO(path));
|
||||
|
||||
if (process.platform === "darwin" && !process.env.SKIP_SIGN) {
|
||||
const identities = execFileSync("security", ["find-identity", "-v", "-p", "codesigning"], { encoding: "utf8" });
|
||||
const identity = identities.match(/"(Developer ID Application: [^"]+)"/)?.[1];
|
||||
if (identity) {
|
||||
for (const bin of binaries) {
|
||||
execFileSync("codesign", ["--force", "--options", "runtime", "--timestamp", "--sign", identity, bin], {
|
||||
stdio: "inherit",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.warn("stage-runtime: no Developer ID identity found, leaving esbuild binaries unsigned");
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`stage-runtime: staged ${externals.join(", ")} at ${stageDir}`);
|
||||
@ -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/. */
|
||||
|
||||
// Stages the agent skills into apps/desktop/skills so electron-forge can ship
|
||||
// them as an app resource (Contents/Resources/skills). The app symlinks agent
|
||||
// skill directories at these staged copies (see src/skills-install.ts), so
|
||||
// auto-updates keep installed skills in lockstep with the dapi they document.
|
||||
//
|
||||
// Prefers a sibling checkout of diffusionstudio/skills next to the repo root
|
||||
// (the dev setup); falls back to a shallow clone (CI).
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const SKILLS_REPO = "https://github.com/diffusionstudio/skills.git";
|
||||
|
||||
const desktopDir = join(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const repoRoot = join(desktopDir, "..", "..");
|
||||
const stageDir = join(desktopDir, "skills");
|
||||
const sibling = join(repoRoot, "..", "skills");
|
||||
|
||||
let sourceDir = sibling;
|
||||
let tempDir = null;
|
||||
if (!existsSync(join(sibling, "editor", "SKILL.md"))) {
|
||||
tempDir = mkdtempSync(join(tmpdir(), "stage-skills-"));
|
||||
execFileSync("git", ["clone", "--depth", "1", SKILLS_REPO, tempDir], { stdio: "inherit" });
|
||||
sourceDir = tempDir;
|
||||
}
|
||||
|
||||
// A skill is a top-level directory with a SKILL.md.
|
||||
const skills = readdirSync(sourceDir, { withFileTypes: true })
|
||||
.filter((e) => e.isDirectory() && !e.name.startsWith("."))
|
||||
.filter((e) => existsSync(join(sourceDir, e.name, "SKILL.md")))
|
||||
.map((e) => e.name);
|
||||
|
||||
if (skills.length === 0) {
|
||||
throw new Error(`stage-skills: no skills found in ${sourceDir}`);
|
||||
}
|
||||
|
||||
rmSync(stageDir, { recursive: true, force: true });
|
||||
mkdirSync(stageDir, { recursive: true });
|
||||
for (const name of skills) {
|
||||
cpSync(join(sourceDir, name), join(stageDir, name), { recursive: true });
|
||||
}
|
||||
if (tempDir) rmSync(tempDir, { recursive: true, force: true });
|
||||
|
||||
console.log(`stage-skills: staged ${skills.join(", ")} at ${stageDir}`);
|
||||
15
apps/desktop/scripts/tray-menu-icons.sh
Executable file
@ -0,0 +1,15 @@
|
||||
#!/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
|
||||
178
apps/desktop/scripts/win-assets.py
Normal file
@ -0,0 +1,178 @@
|
||||
#!/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]()
|
||||
131
apps/desktop/src/agent-chat.ts
Normal file
@ -0,0 +1,131 @@
|
||||
/* 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 { app, utilityProcess } from "electron";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
|
||||
import type { UtilityProcess } from "electron";
|
||||
|
||||
type AgentChatOptions = { dataDir: string; mcpUrl: string | null; version: string };
|
||||
|
||||
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;
|
||||
let options: AgentChatOptions | null = null;
|
||||
let token = "";
|
||||
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");
|
||||
const proc = utilityProcess.fork(path, [], { serviceName: "Agent Chat", stdio: "inherit" });
|
||||
child = proc;
|
||||
|
||||
proc.on("spawn", () => {
|
||||
proc.postMessage({
|
||||
type: "start",
|
||||
config: {
|
||||
token,
|
||||
dataDir: options!.dataDir,
|
||||
mcp: options!.mcpUrl ? { name: "diffusion", url: options!.mcpUrl } : null,
|
||||
version: options!.version,
|
||||
allowedOrigins: app.isPackaged ? ["file://", "null"] : ["file://", "null", DEV_ORIGIN],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
proc.on("message", (message: { type?: string; url?: string; message?: string }) => {
|
||||
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}`);
|
||||
}
|
||||
});
|
||||
|
||||
proc.on("exit", (code) => {
|
||||
if (child !== proc) return;
|
||||
child = null;
|
||||
endpoint = null;
|
||||
if (stopped) return;
|
||||
const delay = RESTART_DELAYS_MS[Math.min(restarts, RESTART_DELAYS_MS.length - 1)]!;
|
||||
restarts += 1;
|
||||
console.error(`[agent-chat] host exited (${code}); restarting in ${delay} ms`);
|
||||
restartTimer = setTimeout(() => {
|
||||
restartTimer = null;
|
||||
spawn();
|
||||
}, delay);
|
||||
});
|
||||
}
|
||||
|
||||
/** Generates the token; the host is forked when it is first needed. Call once, after `whenReady`. */
|
||||
export function configureAgentChat(next: AgentChatOptions): void {
|
||||
options = next;
|
||||
token = randomBytes(32).toString("base64url");
|
||||
stopped = false;
|
||||
restarts = 0;
|
||||
}
|
||||
|
||||
/** 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);
|
||||
});
|
||||
}
|
||||
|
||||
/** 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 });
|
||||
}
|
||||
}
|
||||
|
||||
/** Asks the host to stop (it kills its harness trees), then kills it after a grace period. */
|
||||
export function stopAgentChat(): void {
|
||||
stopped = true;
|
||||
if (restartTimer) clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
const proc = child;
|
||||
child = null;
|
||||
endpoint = null;
|
||||
if (!proc) return;
|
||||
try {
|
||||
proc.postMessage({ type: "stop" });
|
||||
} catch {
|
||||
// Already gone.
|
||||
}
|
||||
const timer = setTimeout(() => proc.kill(), STOP_GRACE_MS);
|
||||
proc.once("exit", () => clearTimeout(timer));
|
||||
}
|
||||
@ -3,69 +3,107 @@
|
||||
* 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 { access, writeFile } from "node:fs/promises";
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export async function startAnalytics(windows: WindowHost): Promise<void> {
|
||||
if (!enabled) return;
|
||||
|
||||
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";
|
||||
setInterval(flush, FLUSH_INTERVAL_MS);
|
||||
setInterval(() => (windows.current() && track("app_used")), 60_000);
|
||||
|
||||
// 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`;
|
||||
}
|
||||
const marker = join(app.getPath("userData"), "install-tracked");
|
||||
const installedAt = await stat(marker).then((info) => info.birthtimeMs, () => null);
|
||||
|
||||
export async function trackInstall(): Promise<void> {
|
||||
if (!app.isPackaged) return;
|
||||
|
||||
const marker = join(app.getPath("userData"), MARKER_FILE);
|
||||
try {
|
||||
await access(marker);
|
||||
return;
|
||||
} catch {
|
||||
// No marker yet — this is the first (tracked) launch.
|
||||
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) });
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
if (!queue.length || !apiUrl || token === undefined) return;
|
||||
const batch = queue.splice(0, BATCH_MAX);
|
||||
try {
|
||||
const response = await fetch(UMAMI_ENDPOINT, {
|
||||
const response = await fetch(`${apiUrl}/api/v2/trpc/events.track`, {
|
||||
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(),
|
||||
},
|
||||
},
|
||||
}),
|
||||
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),
|
||||
});
|
||||
if (response.ok) {
|
||||
await writeFile(marker, new Date().toISOString());
|
||||
}
|
||||
// Sent, or a batch the API will never take (400): either way it is done.
|
||||
if (response.ok || response.status === 400) return;
|
||||
} catch {
|
||||
// Offline or Umami unreachable — retried on the next launch.
|
||||
// Offline or the API unreachable.
|
||||
}
|
||||
|
||||
queue.unshift(...batch);
|
||||
}
|
||||
|
||||
49
apps/desktop/src/atomic.ts
Normal file
@ -0,0 +1,49 @@
|
||||
/* 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/. */
|
||||
|
||||
// Writes that land whole. Anything may be reading a project's files while the
|
||||
// app writes them — a compile, the user's editor, the watcher reading a file
|
||||
// back to see whether it really changed — and a reader that catches a file
|
||||
// halfway through a write sees source no one wrote. So a write goes to a temp
|
||||
// file beside its target and is renamed over it, which the filesystem does in
|
||||
// one step.
|
||||
|
||||
import { rename, unlink, writeFile } from "node:fs/promises";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
|
||||
/**
|
||||
* The prefix every temp file the app writes carries. Recognisable rather than
|
||||
* unique, so the project watcher can ignore the whole class of them without
|
||||
* anyone having to declare each one as it is written.
|
||||
*/
|
||||
export const TEMP_PREFIX = ".dstmp-";
|
||||
|
||||
/** Whether `path` — of any form — names one of our temp files. */
|
||||
export const isTempPath = (path: string): boolean => basename(path).startsWith(TEMP_PREFIX);
|
||||
|
||||
let sequence = 0;
|
||||
|
||||
/**
|
||||
* A free path beside `path` to write at until the content is whole. Beside it
|
||||
* rather than in the system's temp folder, because a rename is only atomic
|
||||
* within a filesystem.
|
||||
*/
|
||||
export function tempPathFor(path: string): string {
|
||||
return join(dirname(path), `${TEMP_PREFIX}${basename(path)}.${process.pid}-${++sequence}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes `text` to `path` as one step: a temp file beside it, renamed over it.
|
||||
* A failed write takes its temp file with it.
|
||||
*/
|
||||
export async function writeFileAtomic(path: string, text: string): Promise<void> {
|
||||
const temp = tempPathFor(path);
|
||||
try {
|
||||
await writeFile(temp, text, "utf8");
|
||||
await rename(temp, path);
|
||||
} catch (error) {
|
||||
await unlink(temp).catch(() => { });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@ -2,46 +2,175 @@
|
||||
* 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 { app } from "electron";
|
||||
import { execFile } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { existsSync, lstatSync, unlinkSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { CliInstallResult } from "./main-channels";
|
||||
import { addShimToPath, removeShimFromPath, shimOnPath, shimPath, writeShim } from "./cli-windows";
|
||||
|
||||
export const CLI_LINK_PATH = "/usr/local/bin/dapi";
|
||||
import type { CliInstallResult, CliStatus, CliUninstallResult } from "./main-channels";
|
||||
|
||||
export const CLI_LINK_DIR = "/usr/local/bin";
|
||||
|
||||
// The dev workflow links the workspace build into Homebrew's bin instead
|
||||
// (`symlink:create` in apps/cli), so both locations count as installed.
|
||||
const DEV_LINK_PATH = "/opt/homebrew/bin/dapi";
|
||||
// (`npm run link` in apps/cli), so that location counts as installed too.
|
||||
const DEV_LINK_DIR = "/opt/homebrew/bin";
|
||||
|
||||
export function isCliInstalled(): boolean {
|
||||
return existsSync(CLI_LINK_PATH) || existsSync(DEV_LINK_PATH);
|
||||
// `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}`);
|
||||
|
||||
/**
|
||||
* Whether `path` is a symlink — dangling or not, since a link left behind
|
||||
* by a deleted bundle is exactly what removal is for. `existsSync` follows
|
||||
* links and would miss that case.
|
||||
*/
|
||||
function isLink(path: string): boolean {
|
||||
return lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink() ?? false;
|
||||
}
|
||||
|
||||
// Linking into /usr/local/bin needs elevation; osascript shows the standard
|
||||
// macOS admin prompt so the app itself never asks for credentials.
|
||||
function linkCli(): Promise<void> {
|
||||
const wrapper = join(process.resourcesPath, "cli", "bin", "dapi");
|
||||
const shell = `mkdir -p /usr/local/bin && ln -sf '${wrapper}' '${CLI_LINK_PATH}'`;
|
||||
/** 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;
|
||||
}
|
||||
}
|
||||
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 };
|
||||
}
|
||||
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`;
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile("osascript", ["-e", script], (err) => (err ? reject(err) : resolve()));
|
||||
});
|
||||
}
|
||||
|
||||
/** 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> {
|
||||
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}`);
|
||||
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 symlink:create` in development.",
|
||||
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 {
|
||||
await linkCli();
|
||||
return { status: "installed" };
|
||||
if (!(await shimOnPath())) return { status: "absent" };
|
||||
await removeShimFromPath();
|
||||
return { status: "removed" };
|
||||
} catch (e) {
|
||||
const message = (e as Error).message ?? "";
|
||||
if (message.includes("-128")) return { status: "cancelled" }; // user cancelled the admin prompt
|
||||
return { status: "error", error: message };
|
||||
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.` };
|
||||
}
|
||||
try {
|
||||
for (const path of present) 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(" ")}`);
|
||||
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,160 +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 { existsSync, unlinkSync } from "node:fs";
|
||||
import { createServer } from "node:net";
|
||||
import type { Server, Socket } from "node:net";
|
||||
import { app, BrowserWindow } from "electron";
|
||||
import { CLI_WIRE, SOCKET_PATH } from "@diffusionstudio/cli/protocol";
|
||||
import type { CliHandshake, CliHandshakeReply } from "@diffusionstudio/cli/protocol";
|
||||
import { mainBridge } from "./main-manager";
|
||||
import { MAIN_CHANNELS } from "./main-channels";
|
||||
|
||||
let cliServer: Server | null = null;
|
||||
let currentWindow: BrowserWindow | null = null;
|
||||
let headless = false;
|
||||
let windowLifecycleBound = false;
|
||||
|
||||
export function isHeadless(): boolean {
|
||||
return headless;
|
||||
}
|
||||
|
||||
function enableHeadless(): void {
|
||||
if (headless) return;
|
||||
headless = true;
|
||||
if (currentWindow && !currentWindow.isDestroyed()) {
|
||||
mainBridge.emit(currentWindow, MAIN_CHANNELS.HEADLESS_MODE, { active: true });
|
||||
}
|
||||
}
|
||||
|
||||
// Resolves once the current window has finished loading.
|
||||
function waitForRendererReady(timeoutMs = 30000): Promise<void> {
|
||||
if (!currentWindow || currentWindow.isDestroyed()) {
|
||||
return Promise.reject(new Error("No window"));
|
||||
}
|
||||
|
||||
if (currentWindow.webContents.isCrashed()) {
|
||||
return Promise.reject(new Error("Renderer crashed"));
|
||||
}
|
||||
if (!currentWindow.webContents.isLoading()) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
console.warn(`[cli-server] renderer not ready after ${timeoutMs}ms`);
|
||||
reject(new Error("App did not become ready in time"));
|
||||
}, timeoutMs);
|
||||
|
||||
const cleanup = () => {
|
||||
clearTimeout(timer);
|
||||
currentWindow?.webContents.off("did-finish-load", onLoad);
|
||||
currentWindow?.webContents.off("did-fail-load", onFail);
|
||||
};
|
||||
|
||||
const onLoad = () => {
|
||||
cleanup();
|
||||
resolve();
|
||||
};
|
||||
|
||||
const onFail = () => {
|
||||
cleanup();
|
||||
reject(new Error(`Renderer failed to load`));
|
||||
};
|
||||
|
||||
currentWindow?.webContents.on("did-finish-load", onLoad);
|
||||
currentWindow?.webContents.on("did-fail-load", onFail);
|
||||
});
|
||||
}
|
||||
|
||||
function bindWindowLifecycle(): void {
|
||||
if (windowLifecycleBound) return;
|
||||
windowLifecycleBound = true;
|
||||
app.on("browser-window-created", (_event, window) => {
|
||||
currentWindow = window;
|
||||
window.on("closed", () => {
|
||||
if (currentWindow === window) currentWindow = null;
|
||||
});
|
||||
});
|
||||
// Catch any window that was created before the server started.
|
||||
const windows = BrowserWindow.getAllWindows();
|
||||
if (windows.length > 0) currentWindow = windows[windows.length - 1]!;
|
||||
}
|
||||
|
||||
// Relays the CLI's connect info to the renderer, which dials the CLI's
|
||||
// WebSocket server directly. The reply confirms delivery only; from there
|
||||
// the request/response traffic bypasses main entirely.
|
||||
async function deliverHandshake(handshake: CliHandshake, sock: Socket): Promise<void> {
|
||||
let reply: CliHandshakeReply;
|
||||
try {
|
||||
await waitForRendererReady();
|
||||
if (!currentWindow || currentWindow.isDestroyed()) {
|
||||
throw new Error("No window");
|
||||
}
|
||||
currentWindow.webContents.send(CLI_WIRE.CONNECT, handshake);
|
||||
reply = { ok: true };
|
||||
} catch (err) {
|
||||
reply = { ok: false, error: (err as Error).message };
|
||||
}
|
||||
if (!sock.destroyed) sock.end(JSON.stringify(reply));
|
||||
}
|
||||
|
||||
export function startCliServer() {
|
||||
cleanupStaleSocket();
|
||||
bindWindowLifecycle();
|
||||
|
||||
cliServer = createServer({ allowHalfOpen: true }, (sock: Socket) => {
|
||||
enableHeadless();
|
||||
let buf = "";
|
||||
sock.setEncoding("utf8");
|
||||
sock.setTimeout(60000, () => sock.destroy());
|
||||
sock.on("data", (chunk) => {
|
||||
buf += chunk;
|
||||
});
|
||||
sock.on("end", async () => {
|
||||
sock.setTimeout(0);
|
||||
let handshake: CliHandshake;
|
||||
try {
|
||||
handshake = JSON.parse(buf) as CliHandshake;
|
||||
if (typeof handshake.port !== "number" || typeof handshake.token !== "string") {
|
||||
throw new Error("Malformed handshake");
|
||||
}
|
||||
} catch {
|
||||
sock.end(JSON.stringify({ ok: false, error: "Invalid handshake" }));
|
||||
return;
|
||||
}
|
||||
await deliverHandshake(handshake, sock);
|
||||
});
|
||||
sock.on("error", () => {
|
||||
// Client hung up; nothing to do.
|
||||
});
|
||||
});
|
||||
|
||||
cliServer.on("error", (err) => {
|
||||
console.error("CLI server error:", err);
|
||||
});
|
||||
|
||||
cliServer.listen(SOCKET_PATH);
|
||||
}
|
||||
|
||||
export function stopCliServer() {
|
||||
if (!cliServer) return;
|
||||
cliServer.close();
|
||||
cliServer = null;
|
||||
cleanupStaleSocket();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up a stale socket file (Unix). Safe because the single-instance lock
|
||||
* guarantees no other instance of ours is running.
|
||||
*/
|
||||
function cleanupStaleSocket() {
|
||||
try {
|
||||
if (process.platform !== "win32" && existsSync(SOCKET_PATH)) {
|
||||
unlinkSync(SOCKET_PATH);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort.
|
||||
}
|
||||
}
|
||||
57
apps/desktop/src/cli-windows.test.ts
Normal file
@ -0,0 +1,57 @@
|
||||
/* 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);
|
||||
});
|
||||
});
|
||||
151
apps/desktop/src/cli-windows.ts
Normal file
@ -0,0 +1,151 @@
|
||||
/* 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);
|
||||
}
|
||||
47
apps/desktop/src/clipboard.ts
Normal file
@ -0,0 +1,47 @@
|
||||
/* 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, "&");
|
||||
}
|
||||
49
apps/desktop/src/cloud-sync-windows.test.ts
Normal file
@ -0,0 +1,49 @@
|
||||
/* 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();
|
||||
});
|
||||
});
|
||||
89
apps/desktop/src/cloud-sync-windows.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/. */
|
||||
|
||||
// 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;
|
||||
}
|
||||
56
apps/desktop/src/dapi/docs.test.ts
Normal file
@ -0,0 +1,56 @@
|
||||
/* 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 { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { instructions } from "./docs";
|
||||
|
||||
// The docs in miniature, laid out like the repo's `docs/`.
|
||||
const root = mkdtempSync(join(tmpdir(), "dapi-docs-"));
|
||||
const docsDir = join(root, "docs");
|
||||
const repoDocs = join(__dirname, "..", "..", "..", "..", "docs");
|
||||
|
||||
beforeAll(() => {
|
||||
mkdirSync(join(docsDir, "skills"), { recursive: true });
|
||||
writeFileSync(join(docsDir, "INSTRUCTIONS.md"), "Diffusion Studio is running.\n\nRead `skills/editor.md`.\n");
|
||||
writeFileSync(join(docsDir, "skills", "editor.md"), "# Editing\n\nHow to edit.\n");
|
||||
writeFileSync(join(docsDir, "skills", "watch.md"), "# Watching\n\nHow to watch.\n");
|
||||
});
|
||||
|
||||
afterAll(() => rmSync(root, { recursive: true, force: true }));
|
||||
|
||||
describe("instructions", () => {
|
||||
it("is INSTRUCTIONS.md verbatim, followed by where the docs sit on disk", () => {
|
||||
const text = instructions(docsDir);
|
||||
expect(text.startsWith("Diffusion Studio is running.\n\nRead `skills/editor.md`.")).toBe(true);
|
||||
expect(text).toContain(`The docs, including every page named above, are the files at \`${docsDir}\``);
|
||||
});
|
||||
|
||||
it("falls back to a one-liner when nothing is staged", () => {
|
||||
const text = instructions(null);
|
||||
expect(text).toContain("The tools are the whole API");
|
||||
expect(text).not.toContain("skills/editor.md");
|
||||
});
|
||||
|
||||
it("builds from the repo's own docs without broken instructions", () => {
|
||||
if (!existsSync(repoDocs)) return;
|
||||
const text = instructions(repoDocs);
|
||||
expect(text).toContain(repoDocs);
|
||||
expect(text).not.toContain("dapi://");
|
||||
expect(text).not.toContain("\\`");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the repo's INSTRUCTIONS.md", () => {
|
||||
it("names the skills, and every page it names exists", () => {
|
||||
if (!existsSync(repoDocs)) return;
|
||||
const text = readFileSync(join(repoDocs, "INSTRUCTIONS.md"), "utf8");
|
||||
const pages = [...text.matchAll(/`((?:skills|reference|guides|examples|brand)\/[^`]*?\.(?:md|tsx?))`/g)].map((m) => m[1]);
|
||||
expect(pages).toContain("skills/editor.md");
|
||||
expect(pages).toContain("skills/watch.md");
|
||||
for (const page of pages) expect(existsSync(join(repoDocs, ...page.split("/")))).toBe(true);
|
||||
});
|
||||
});
|
||||
36
apps/desktop/src/dapi/docs.ts
Normal file
@ -0,0 +1,36 @@
|
||||
/* 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 { readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export const INSTRUCTIONS_FILE = "INSTRUCTIONS.md";
|
||||
|
||||
const FALLBACK_INSTRUCTIONS =
|
||||
"Diffusion Studio, a video editor, is running on this machine and you are connected to it. The tools are the whole API; their descriptions are authoritative.";
|
||||
|
||||
/**
|
||||
* The text every client gets on connect: INSTRUCTIONS.md from the docs, then
|
||||
* where the docs sit on disk. The page names the skills and everything else
|
||||
* it wants read — adding one is editing that file, not this one; the paths in
|
||||
* it are relative to the docs, and the sentence below is what anchors them.
|
||||
*/
|
||||
export function instructions(docsDir: string | null): string {
|
||||
const text = docsDir ? readText(join(docsDir, INSTRUCTIONS_FILE)) : null;
|
||||
const parts = [text?.trim() || FALLBACK_INSTRUCTIONS];
|
||||
if (docsDir) {
|
||||
parts.push(
|
||||
`The docs, including every page named above, are the files at \`${docsDir}\`: the skills, the tool and JSX reference, guides, runnable examples, and the brand kit (fonts, imagery, components to copy). They belong to the app; read them, never edit them.`,
|
||||
);
|
||||
}
|
||||
return parts.join("\n\n");
|
||||
}
|
||||
|
||||
function readText(path: string): string | null {
|
||||
try {
|
||||
return readFileSync(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
34
apps/desktop/src/dapi/handler.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/* 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 { 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. */
|
||||
signal: AbortSignal;
|
||||
/** The app's console buffer, oldest first. */
|
||||
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";
|
||||
|
||||
export type MainHandler<N extends MainToolName> = (args: ToolArgs<N>, ctx: MainContext) => Promise<ToolResult<N>>;
|
||||
|
||||
export type MainHandlers = { readonly [N in MainToolName]: MainHandler<N> };
|
||||
12
apps/desktop/src/dapi/handlers/index.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/* 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 { logs } from "./logs";
|
||||
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 };
|
||||
43
apps/desktop/src/dapi/handlers/logs.test.ts
Normal file
@ -0,0 +1,43 @@
|
||||
/* 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 { LOG_MESSAGE_MAX, LOG_TAIL } from "@diffusionstudio/dapi";
|
||||
import { logs } from "./logs";
|
||||
|
||||
import type { LogEntry } from "@diffusionstudio/dapi";
|
||||
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 });
|
||||
|
||||
describe("logs", () => {
|
||||
it("returns the last LOG_TAIL entries when no tail is given", async () => {
|
||||
const buffer = Array.from({ length: LOG_TAIL + 5 }, (_, i) => entry(i, `m${i}`));
|
||||
const { entries } = await logs({}, ctx(buffer));
|
||||
expect(entries).toHaveLength(LOG_TAIL);
|
||||
expect(entries[0]!.ts).toBe(5);
|
||||
});
|
||||
|
||||
it("filters by level, since, and contains before taking the tail", async () => {
|
||||
const buffer = [
|
||||
entry(1, "Export 10%"),
|
||||
entry(2, "export 50%"),
|
||||
entry(3, "render done"),
|
||||
entry(4, "EXPORT failed", "error"),
|
||||
entry(5, "export 90%", "debug"),
|
||||
];
|
||||
const { entries } = await logs({ since: 1, contains: "export", level: "info", tail: 1 }, ctx(buffer));
|
||||
expect(entries.map((e) => e.ts)).toEqual([4]);
|
||||
const all = await logs({ since: 1, contains: "export" }, ctx(buffer));
|
||||
expect(all.entries.map((e) => e.ts)).toEqual([2, 4, 5]);
|
||||
});
|
||||
|
||||
it("cuts long messages and says how much was dropped", async () => {
|
||||
const { entries } = await logs({}, ctx([entry(1, "x".repeat(LOG_MESSAGE_MAX + 10))]));
|
||||
expect(entries[0]!.message).toBe(`${"x".repeat(LOG_MESSAGE_MAX)}… (10 more chars)`);
|
||||
});
|
||||
});
|
||||
38
apps/desktop/src/dapi/handlers/logs.ts
Normal file
@ -0,0 +1,38 @@
|
||||
/* 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 { LOG_MESSAGE_MAX, LOG_TAIL } from "@diffusionstudio/dapi";
|
||||
|
||||
import type { LogEntry, LogLevel } from "@diffusionstudio/dapi";
|
||||
import type { MainHandler } from "../handler";
|
||||
|
||||
const LEVEL_RANK: Record<LogLevel, number> = { debug: 0, info: 1, warning: 2, error: 3 };
|
||||
|
||||
export const logs: MainHandler<"logs"> = async ({ tail = LOG_TAIL, level, since, contains }, ctx) => {
|
||||
const min = level === undefined ? 0 : LEVEL_RANK[level];
|
||||
const needle = contains?.toLowerCase();
|
||||
const entries = ctx
|
||||
.logs()
|
||||
.filter(
|
||||
(e) =>
|
||||
LEVEL_RANK[e.level] >= min &&
|
||||
(since === undefined || e.ts > since) &&
|
||||
(needle === undefined || e.message.toLowerCase().includes(needle)),
|
||||
);
|
||||
return { entries: entries.slice(-tail).map(clip) };
|
||||
};
|
||||
|
||||
function clip(entry: LogEntry): LogEntry {
|
||||
const over = entry.message.length - LOG_MESSAGE_MAX;
|
||||
return over > 0 ? { ...entry, message: `${entry.message.slice(0, LOG_MESSAGE_MAX)}… (${over} more chars)` } : entry;
|
||||
}
|
||||
|
||||
/** One log entry as a line: local time, level, message, source. */
|
||||
export function formatLogEntry(entry: LogEntry): string {
|
||||
const pad = (n: number, w = 2) => String(n).padStart(w, "0");
|
||||
const d = new Date(entry.ts);
|
||||
const time = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(), 3)}`;
|
||||
const source = entry.source ? ` (${entry.source})` : "";
|
||||
return `${time} [${entry.level}] ${entry.message}${source}`;
|
||||
}
|
||||
@ -4,50 +4,41 @@
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { arch, platform, release } from "node:os";
|
||||
import { DapiError, ISSUE_LOG_TAIL } from "@diffusionstudio/dapi";
|
||||
import { formatLogEntry } from "./logs";
|
||||
|
||||
import type { MainHandler } from "../handler";
|
||||
|
||||
const REPO = "diffusionstudio/editor";
|
||||
|
||||
export const GH_MISSING =
|
||||
const GH_MISSING =
|
||||
"gh (GitHub CLI) is not installed, so the issue cannot be filed. Install it from https://cli.github.com, run `gh auth login`, then retry.";
|
||||
|
||||
export type IssueInput = {
|
||||
title: string;
|
||||
body?: string;
|
||||
commands?: string[];
|
||||
logs?: string[]; // already formatted log lines, oldest first
|
||||
appStatus: string; // "running", "not running", "not checked", or why it was unreachable
|
||||
version: string;
|
||||
};
|
||||
|
||||
function fence(language: string, content: string): string {
|
||||
return `\`\`\`${language}\n${content}\n\`\`\``;
|
||||
}
|
||||
|
||||
function environmentTable(input: IssueInput): string {
|
||||
function environmentTable(version: string): string {
|
||||
const rows: Array<[string, string]> = [
|
||||
["dapi", input.version],
|
||||
["app", version],
|
||||
["platform", `${platform()} ${release()} (${arch()})`],
|
||||
["node", process.version],
|
||||
["app", input.appStatus],
|
||||
["electron", process.versions.electron ?? "unknown"],
|
||||
];
|
||||
return ["| | |", "| --- | --- |", ...rows.map(([k, v]) => `| ${k} | ${v} |`)].join("\n");
|
||||
}
|
||||
|
||||
export function buildIssueBody(input: IssueInput): string {
|
||||
function buildIssueBody(input: { body?: string; commands?: string[]; logs: string[]; version: string }): string {
|
||||
const sections: string[] = [];
|
||||
|
||||
if (input.body?.trim()) sections.push(input.body.trim());
|
||||
if (input.commands?.length) sections.push(`## Repro\n\n${fence("sh", input.commands.join("\n"))}`);
|
||||
sections.push(`## Environment\n\n${environmentTable(input)}`);
|
||||
if (input.logs?.length) sections.push(`## App logs\n\n${fence("", input.logs.join("\n"))}`);
|
||||
|
||||
sections.push(`## Environment\n\n${environmentTable(input.version)}`);
|
||||
if (input.logs.length) sections.push(`## App logs\n\n${fence("", input.logs.join("\n"))}`);
|
||||
return `${sections.join("\n\n")}\n`;
|
||||
}
|
||||
|
||||
// --repo is explicit because dapi runs from the user's project, not a checkout
|
||||
// of the editor; the body goes over stdin so a long log tail can't blow the
|
||||
// argv size limit.
|
||||
export function createIssue(title: string, body: string): Promise<string> {
|
||||
// --repo is explicit because the app is not a checkout of the editor; the body
|
||||
// goes over stdin so a long log tail can't blow the argv size limit.
|
||||
function createIssue(title: string, body: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const gh = spawn("gh", ["issue", "create", "--repo", REPO, "--title", title, "--body-file", "-"]);
|
||||
|
||||
@ -57,7 +48,7 @@ export function createIssue(title: string, body: string): Promise<string> {
|
||||
gh.stderr.on("data", (chunk) => (stderr += chunk));
|
||||
|
||||
gh.on("error", (e) => {
|
||||
reject((e as NodeJS.ErrnoException).code === "ENOENT" ? new Error(GH_MISSING) : e);
|
||||
reject((e as NodeJS.ErrnoException).code === "ENOENT" ? new DapiError("unsupported", GH_MISSING) : e);
|
||||
});
|
||||
gh.on("close", (code) => {
|
||||
if (code !== 0) {
|
||||
@ -73,7 +64,16 @@ export function createIssue(title: string, body: string): Promise<string> {
|
||||
resolve(url);
|
||||
});
|
||||
|
||||
gh.stdin.on("error", () => { }); // gh exiting early (auth failure) breaks the pipe
|
||||
gh.stdin.on("error", () => {}); // gh exiting early (auth failure) breaks the pipe
|
||||
gh.stdin.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
export const report: MainHandler<"report"> = async ({ title, body, commands, logs }, ctx) => {
|
||||
const summary = title.trim();
|
||||
if (!summary) throw new DapiError("invalid-input", "A one-line title is required.");
|
||||
const tail = logs ?? ISSUE_LOG_TAIL;
|
||||
const lines = tail > 0 ? ctx.logs().slice(-tail).map(formatLogEntry) : [];
|
||||
const url = await createIssue(summary, buildIssueBody({ body, commands, logs: lines, version: ctx.version }));
|
||||
return { url };
|
||||
};
|
||||
15
apps/desktop/src/dapi/handlers/window.ts
Normal file
@ -0,0 +1,15 @@
|
||||
/* 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() };
|
||||
};
|
||||
96
apps/desktop/src/dapi/http.test.ts
Normal file
@ -0,0 +1,96 @@
|
||||
/* 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 { request } from "node:http";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { DapiHttpServer } from "./http";
|
||||
|
||||
// An ephemeral port: the fixed one may be held by a running app.
|
||||
const PORT = 3200 + Math.floor(Math.random() * 500);
|
||||
const PATH = "/mcp";
|
||||
let server: DapiHttpServer;
|
||||
let sessionsCreated = 0;
|
||||
|
||||
beforeAll(async () => {
|
||||
server = new DapiHttpServer({
|
||||
host: "127.0.0.1",
|
||||
port: PORT,
|
||||
path: PATH,
|
||||
createSession() {
|
||||
sessionsCreated++;
|
||||
const session = new McpServer({ name: "test", version: "0.0.0" }, { instructions: "Test instructions." });
|
||||
session.registerTool(
|
||||
"echo",
|
||||
{ inputSchema: z.object({ text: z.string() }), outputSchema: z.object({ text: z.string() }) },
|
||||
async ({ text }) => ({ content: [{ type: "text", text }], structuredContent: { text } }),
|
||||
);
|
||||
session.registerResource("note", "dapi://note", { mimeType: "text/plain" }, async () => ({
|
||||
contents: [{ uri: "dapi://note", mimeType: "text/plain", text: "hello" }],
|
||||
}));
|
||||
return session;
|
||||
},
|
||||
});
|
||||
await server.start();
|
||||
});
|
||||
|
||||
afterAll(() => server.stop());
|
||||
|
||||
async function connect(): Promise<Client> {
|
||||
const client = new Client({ name: "test-client", version: "0.0.0" });
|
||||
await client.connect(new StreamableHTTPClientTransport(new URL(server.url)));
|
||||
return client;
|
||||
}
|
||||
|
||||
describe("mcp over http", () => {
|
||||
it("serves a session: instructions, tools, resources", async () => {
|
||||
const client = await connect();
|
||||
expect(client.getInstructions()).toBe("Test instructions.");
|
||||
expect((await client.listTools()).tools.map((t) => t.name)).toEqual(["echo"]);
|
||||
const result = await client.callTool({ name: "echo", arguments: { text: "hi" } });
|
||||
expect(result.structuredContent).toEqual({ text: "hi" });
|
||||
const note = await client.readResource({ uri: "dapi://note" });
|
||||
expect(note.contents[0]).toMatchObject({ text: "hello" });
|
||||
await client.close();
|
||||
});
|
||||
|
||||
it("gives each client its own session", async () => {
|
||||
const before = sessionsCreated;
|
||||
const a = await connect();
|
||||
const b = await connect();
|
||||
expect(sessionsCreated - before).toBe(2);
|
||||
await a.close();
|
||||
await b.close();
|
||||
});
|
||||
|
||||
it("rejects a stale session id and a non-mcp path", async () => {
|
||||
const stale = await fetch(server.url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", accept: "application/json, text/event-stream", "mcp-session-id": "nope" },
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
|
||||
});
|
||||
expect(stale.status).toBe(404);
|
||||
const elsewhere = await fetch(`http://127.0.0.1:${PORT}/other`);
|
||||
expect(elsewhere.status).toBe(404);
|
||||
});
|
||||
|
||||
it("rejects a request whose Host is not loopback (dns rebinding)", async () => {
|
||||
// node's fetch drops a custom Host header, so go through node:http.
|
||||
const status = await new Promise<number>((resolve, reject) => {
|
||||
const req = request(
|
||||
{ host: "127.0.0.1", port: PORT, path: PATH, method: "POST", headers: { host: "evil.example", "content-type": "application/json", accept: "application/json, text/event-stream" } },
|
||||
(res) => {
|
||||
res.resume();
|
||||
res.on("end", () => resolve(res.statusCode ?? 0));
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.end(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "x", version: "0" } } }));
|
||||
});
|
||||
expect(status).toBe(403);
|
||||
});
|
||||
});
|
||||
126
apps/desktop/src/dapi/http.ts
Normal file
@ -0,0 +1,126 @@
|
||||
/* 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/. */
|
||||
|
||||
// MCP over Streamable HTTP on a fixed loopback port: the transport agents
|
||||
// register by URL. One MCP session per client, keyed by the session id the
|
||||
// transport hands out on `initialize`; later requests carry it in a header.
|
||||
// No token: the server binds to loopback and rejects any Host header that is
|
||||
// not the loopback address, which is what keeps browser pages from reaching
|
||||
// it. Everything else running as the user can already reach the app.
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { createServer } from "node:http";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
|
||||
import type { IncomingMessage, Server, ServerResponse } from "node:http";
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
|
||||
export type HttpServerDeps = {
|
||||
host: string;
|
||||
port: number;
|
||||
/** The URL path the endpoint answers on; anything else is 404. */
|
||||
path: string;
|
||||
/** A fresh MCP server with the tools and resources registered, one per session. */
|
||||
createSession(): McpServer;
|
||||
};
|
||||
|
||||
type Session = { transport: StreamableHTTPServerTransport; server: McpServer };
|
||||
|
||||
const SESSION_HEADER = "mcp-session-id";
|
||||
|
||||
export class DapiHttpServer {
|
||||
private readonly deps: HttpServerDeps;
|
||||
private readonly sessions = new Map<string, Session>();
|
||||
private server: Server | null = null;
|
||||
|
||||
constructor(deps: HttpServerDeps) {
|
||||
this.deps = deps;
|
||||
}
|
||||
|
||||
/** Resolves once listening; rejects when the port is taken, so the caller can say so. */
|
||||
start(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = createServer((req, res) => void this.handle(req, res));
|
||||
server.once("error", reject);
|
||||
server.listen(this.deps.port, this.deps.host, () => {
|
||||
server.off("error", reject);
|
||||
server.on("error", (error) => console.error("[dapi] http server error:", error));
|
||||
this.server = server;
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
for (const { transport, server } of this.sessions.values()) {
|
||||
void transport.close();
|
||||
void server.close();
|
||||
}
|
||||
this.sessions.clear();
|
||||
this.server?.close();
|
||||
this.server = null;
|
||||
}
|
||||
|
||||
get url(): string {
|
||||
return `http://${this.deps.host}:${this.deps.port}${this.deps.path}`;
|
||||
}
|
||||
|
||||
private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
const url = new URL(req.url ?? "/", this.url);
|
||||
if (url.pathname !== this.deps.path) {
|
||||
res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const id = header(req, SESSION_HEADER);
|
||||
const existing = id === undefined ? undefined : this.sessions.get(id);
|
||||
if (existing) {
|
||||
await existing.transport.handleRequest(req, res);
|
||||
return;
|
||||
}
|
||||
if (id !== undefined) {
|
||||
// The transport would answer the same way; answering here keeps a
|
||||
// stale id from allocating a server it never initializes.
|
||||
res.writeHead(404, { "content-type": "application/json" }).end(
|
||||
JSON.stringify({ jsonrpc: "2.0", error: { code: -32001, message: "Session not found" }, id: null }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
// 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);
|
||||
} 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 {
|
||||
const server = this.deps.createSession();
|
||||
const hosts = [this.deps.host, "localhost"];
|
||||
const transport = new StreamableHTTPServerTransport({
|
||||
sessionIdGenerator: () => randomUUID(),
|
||||
enableDnsRebindingProtection: true,
|
||||
allowedHosts: [...hosts, ...hosts.map((host) => `${host}:${this.deps.port}`)],
|
||||
onsessioninitialized: (id) => {
|
||||
this.sessions.set(id, session);
|
||||
},
|
||||
onsessionclosed: (id) => {
|
||||
this.sessions.delete(id);
|
||||
},
|
||||
});
|
||||
const session: Session = { transport, server };
|
||||
transport.onclose = () => {
|
||||
if (transport.sessionId !== undefined) this.sessions.delete(transport.sessionId);
|
||||
};
|
||||
// connect() starts the transport; it does not block on I/O.
|
||||
void server.connect(transport);
|
||||
return session;
|
||||
}
|
||||
}
|
||||
|
||||
function header(req: IncomingMessage, name: string): string | undefined {
|
||||
const value = req.headers[name];
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
180
apps/desktop/src/dapi/present.test.ts
Normal file
@ -0,0 +1,180 @@
|
||||
/* 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 { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { basename, dirname, join } from "node:path";
|
||||
import { afterAll, describe, expect, it, vi } from "vitest";
|
||||
import { present, toCallToolResult } from "./present";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "dapi-present-"));
|
||||
afterAll(() => rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
const png = (byte: number, size = 8) => new Uint8Array(size).fill(byte);
|
||||
|
||||
describe("present", () => {
|
||||
it("writes capture frames by timecode into the requested directory and returns their paths", async () => {
|
||||
const out = join(dir, "frames");
|
||||
const presented = await present("capture", { id: "intro", output: out }, [
|
||||
{ timecode: "0f", png: png(1) },
|
||||
{ timecode: "1s", png: png(2) },
|
||||
]);
|
||||
expect(presented.output).toEqual({ images: [{ timecode: "0f", path: join(out, "0f.png") }, { timecode: "1s", path: join(out, "1s.png") }] });
|
||||
expect(readFileSync(join(out, "1s.png"))).toEqual(Buffer.from(png(2)));
|
||||
});
|
||||
|
||||
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 { path } = (presented.output as { images: Array<{ path: string }> }).images[0]!;
|
||||
expect(path).toMatch(/dapi-grab-.*[\\/]0f\.png$/);
|
||||
rmSync(join(path, ".."), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
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 }] });
|
||||
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 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 transcriptPath = (transcript.output as { path: string }).path;
|
||||
expect(transcriptPath).toMatch(/dapi-transcript-.*\.json$/);
|
||||
expect(JSON.parse(readFileSync(transcriptPath, "utf8"))).toEqual({ segments: [] });
|
||||
});
|
||||
|
||||
it("names screenshots by time and never overwrites one", async () => {
|
||||
const first = await present("screenshot", { output: dir }, { png: png(5), width: 10, height: 10 });
|
||||
const second = await present("screenshot", { output: dir }, { png: png(6), width: 10, height: 10 });
|
||||
const a = (first.output as { path: string }).path;
|
||||
const b = (second.output as { path: string }).path;
|
||||
expect(a).toMatch(/diffusion-studio_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.png$/);
|
||||
expect(b).not.toBe(a);
|
||||
});
|
||||
|
||||
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 });
|
||||
expect(presented).toEqual({ output: { path: file, segments: 1, words: 2 }, images: [] });
|
||||
expect(JSON.parse(readFileSync(file, "utf8"))).toEqual({ segments });
|
||||
});
|
||||
|
||||
it("passes other results through untouched", async () => {
|
||||
expect(await present("check", { id: "x" }, { stats: {}, issues: [] })).toEqual({ output: { stats: {}, issues: [] }, images: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("toCallToolResult", () => {
|
||||
it("inlines a few small images and always carries the output as text and structure", () => {
|
||||
const result = toCallToolResult({ output: { images: [] }, images: [{ path: "/a.png", png: png(1) }] });
|
||||
expect(result.structuredContent).toEqual({ images: [] });
|
||||
expect(result.content[0]).toEqual({ type: "text", text: '{"images":[]}' });
|
||||
expect(result.content[1]).toMatchObject({ type: "image", mimeType: "image/png" });
|
||||
});
|
||||
|
||||
it("sends paths only when there are many images or a large one", () => {
|
||||
const many = Array.from({ length: 5 }, (_, i) => ({ path: `/${i}.png`, png: png(i) }));
|
||||
expect(toCallToolResult({ output: {}, images: many }).content).toHaveLength(1);
|
||||
const large = [{ path: "/big.png", png: png(0, (1 << 20) + 1) }];
|
||||
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 });
|
||||
});
|
||||
});
|
||||
207
apps/desktop/src/dapi/present.ts
Normal file
@ -0,0 +1,207 @@
|
||||
/* 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 { existsSync, realpathSync } 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 { 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";
|
||||
|
||||
/** A file the tool wrote, kept in memory only long enough to decide whether to inline it. */
|
||||
export type WrittenImage = { path: string; png: Uint8Array };
|
||||
|
||||
export type Presented = { output: unknown; images: WrittenImage[] };
|
||||
|
||||
/** More than this, or any image larger than INLINE_MAX_BYTES, and the caller gets paths only. */
|
||||
const INLINE_MAX_IMAGES = 4;
|
||||
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 "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);
|
||||
default:
|
||||
return { output: result, images: [] };
|
||||
}
|
||||
}
|
||||
|
||||
// Frames and contact sheets arrive in the same shape: each image is stamped
|
||||
// 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}-`)));
|
||||
await mkdir(dir, { recursive: true });
|
||||
const written: WrittenImage[] = [];
|
||||
const refs: ToolOutput<"capture">["images"] = [];
|
||||
for (const { timecode, png } of images) {
|
||||
const path = join(dir, `${timecode}.png`);
|
||||
await writeFile(path, png);
|
||||
written.push({ path, png });
|
||||
refs.push({ timecode, path });
|
||||
}
|
||||
return { output: { images: refs }, images: written };
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a single-file tool writes: `output` when given, a fresh name under
|
||||
* the temp dir otherwise. An `output` that names an existing directory gets
|
||||
* 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);
|
||||
const existing = await stat(output).catch(() => null);
|
||||
if (existing?.isDirectory()) return join(output, name);
|
||||
await mkdir(dirname(output), { recursive: true });
|
||||
return output;
|
||||
}
|
||||
|
||||
async function presentPreview(
|
||||
result: { png: Uint8Array } & Record<string, unknown>,
|
||||
output: string | undefined,
|
||||
kind: string,
|
||||
): Promise<Presented> {
|
||||
const { png, ...rest } = result;
|
||||
const path = await singleFilePath(output, `dapi-${kind}-${randomUUID()}.png`);
|
||||
await writeFile(path, png);
|
||||
return { output: { path, ...rest }, images: [{ path, png }] };
|
||||
}
|
||||
|
||||
async function presentScreenshot(result: ToolResult<"screenshot">, output: string | undefined): Promise<Presented> {
|
||||
const dir = output ?? tempDir();
|
||||
await mkdir(dir, { recursive: true });
|
||||
const taken = new Date();
|
||||
let attempt = 1;
|
||||
let path = join(dir, screenshotFilename(taken, attempt));
|
||||
while (existsSync(path)) path = join(dir, screenshotFilename(taken, ++attempt));
|
||||
await writeFile(path, result.png);
|
||||
const presented: ToolOutput<"screenshot"> = { path, width: result.width, height: result.height };
|
||||
return { output: presented, images: [{ path, png: result.png }] };
|
||||
}
|
||||
|
||||
async function presentTranscript(transcript: ToolResult<"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 };
|
||||
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("-");
|
||||
const time = [pad(taken.getHours()), pad(taken.getMinutes()), pad(taken.getSeconds())].join("-");
|
||||
return `${APP_SLUG}_${date}_${time}${attempt > 1 ? `-${attempt}` : ""}.png`;
|
||||
}
|
||||
|
||||
/** The MCP result: the output as text and structured content, plus the images when they are few and small. */
|
||||
export function toCallToolResult({ output, images }: Presented): CallToolResult {
|
||||
const content: CallToolResult["content"] = [{ type: "text", text: JSON.stringify(output) }];
|
||||
const inline = images.length <= INLINE_MAX_IMAGES && images.every((image) => image.png.byteLength <= INLINE_MAX_BYTES);
|
||||
if (inline) {
|
||||
for (const { png } of images) {
|
||||
content.push({ type: "image", data: Buffer.from(png).toString("base64"), mimeType: "image/png" });
|
||||
}
|
||||
}
|
||||
return { content, structuredContent: output as Record<string, unknown> };
|
||||
}
|
||||
|
||||
/** A failure the agent reads as a sentence, not a protocol error. */
|
||||
export function toErrorResult(error: unknown): CallToolResult {
|
||||
return { isError: true, content: [{ type: "text", text: (error as Error).message }] };
|
||||
}
|
||||
163
apps/desktop/src/dapi/renderer-calls.ts
Normal file
@ -0,0 +1,163 @@
|
||||
/* 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 { randomUUID } from "node:crypto";
|
||||
import { 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 = {
|
||||
resolve(data: unknown): void;
|
||||
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.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
ipcMain.on(DAPI_WIRE.REPLY, (_event, reply: DapiReply) => {
|
||||
const call = this.inFlight.get(reply.id);
|
||||
if (!call) return;
|
||||
this.inFlight.delete(reply.id);
|
||||
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));
|
||||
});
|
||||
}
|
||||
|
||||
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 id = randomUUID();
|
||||
return new Promise((resolve, reject) => {
|
||||
const onAbort = () => {
|
||||
this.inFlight.delete(id);
|
||||
if (!window.isDestroyed()) window.webContents.send(DAPI_WIRE.CANCEL, { id } satisfies DapiCancel);
|
||||
reject(new DapiError("canceled", "The call was canceled."));
|
||||
};
|
||||
signal.addEventListener("abort", onAbort, { once: true });
|
||||
this.inFlight.set(id, {
|
||||
resolve: (data) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
resolve(data);
|
||||
},
|
||||
reject: (error) => {
|
||||
signal.removeEventListener("abort", onAbort);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
window.webContents.send(DAPI_WIRE.CALL, { id, tool, args } satisfies DapiCall);
|
||||
});
|
||||
}
|
||||
|
||||
private track(window: BrowserWindow): void {
|
||||
if (this.tracked.has(window)) return;
|
||||
this.tracked.add(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;
|
||||
this.failAll("The app window closed before replying");
|
||||
});
|
||||
}
|
||||
|
||||
private failAll(message: string): void {
|
||||
const calls = [...this.inFlight.values()];
|
||||
this.inFlight.clear();
|
||||
for (const call of calls) call.reject(new Error(message));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 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);
|
||||
});
|
||||
}
|
||||
138
apps/desktop/src/dapi/server.ts
Normal file
@ -0,0 +1,138 @@
|
||||
/* 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 { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { MCP_HOST, MCP_PATH, MCP_PORT, isDapiError, 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";
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*/
|
||||
const SERVER_NAME = "diffusion";
|
||||
|
||||
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;
|
||||
};
|
||||
/** 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
|
||||
* 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 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`);
|
||||
}
|
||||
}
|
||||
this.http = new DapiHttpServer({
|
||||
host: MCP_HOST,
|
||||
port: MCP_PORT,
|
||||
path: MCP_PATH,
|
||||
createSession: () => this.createSession(),
|
||||
});
|
||||
}
|
||||
|
||||
/** The URL agents register. */
|
||||
get url(): string {
|
||||
return this.http.url;
|
||||
}
|
||||
|
||||
start(): void {
|
||||
this.renderer.start();
|
||||
// A taken port is the one way this fails. The app is still usable
|
||||
// without agents, so it is logged, not fatal; `mcpUrl()` says so.
|
||||
this.httpReady = this.http.start().then(
|
||||
() => true,
|
||||
(error: Error) => {
|
||||
console.error(`[dapi] cannot serve MCP at ${this.url}: ${error.message}`);
|
||||
return false;
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** The HTTP URL once it is being served; null when the port could not be bound. */
|
||||
async mcpUrl(): Promise<string | null> {
|
||||
return (await this.httpReady) ? this.url : null;
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.http.stop();
|
||||
}
|
||||
|
||||
/** One MCP server over the whole catalog. The docs and skills are plain files; the instructions say where. */
|
||||
private createSession(): McpServer {
|
||||
this.instructionsText ??= instructions(this.deps.docsDir);
|
||||
// `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),
|
||||
});
|
||||
}
|
||||
});
|
||||
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 };
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
69
apps/desktop/src/dapi/tools-session.test.ts
Normal file
@ -0,0 +1,69 @@
|
||||
/* 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 { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
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 }> = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
const session = new McpServer({ name: "test", version: "0.0.0" });
|
||||
serveCatalog(session, async (tool, args) => {
|
||||
calls.push({ name: tool.name, args });
|
||||
switch (tool.name) {
|
||||
case "context":
|
||||
return CONTEXT;
|
||||
case "check":
|
||||
throw new Error("No project open — run open first");
|
||||
default:
|
||||
return {};
|
||||
}
|
||||
});
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
await session.connect(serverTransport);
|
||||
client = new Client({ name: "test-client", version: "0.0.0" });
|
||||
await client.connect(clientTransport);
|
||||
});
|
||||
|
||||
afterAll(() => client.close());
|
||||
|
||||
describe("serveCatalog", () => {
|
||||
it("lists every tool with its schemas in JSON Schema 2020-12, the dialect clients validate", async () => {
|
||||
const listed = (await client.listTools()).tools;
|
||||
expect(listed.map((tool) => tool.name)).toEqual(tools.map((tool) => tool.name));
|
||||
for (const tool of listed) {
|
||||
expect(tool.inputSchema.$schema, `${tool.name} input`).toBe(JSON_SCHEMA_DIALECT);
|
||||
expect(tool.outputSchema?.$schema, `${tool.name} output`).toBe(JSON_SCHEMA_DIALECT);
|
||||
expect(tool.description, tool.name).toBeTruthy();
|
||||
}
|
||||
const fonts = listed.find((tool) => tool.name === "fonts")!;
|
||||
expect(fonts.inputSchema.properties).toHaveProperty("family");
|
||||
expect(fonts.outputSchema?.properties).toHaveProperty("families");
|
||||
});
|
||||
|
||||
it("validates arguments before the tool runs, and runs it with the parsed ones", async () => {
|
||||
const before = calls.length;
|
||||
const bad = await client.callTool({ name: "fonts", arguments: { limit: 0 } });
|
||||
expect(bad.isError).toBe(true);
|
||||
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: {} });
|
||||
});
|
||||
|
||||
it("returns a handler's failure as a readable error result, not a protocol error", async () => {
|
||||
const result = await client.callTool({ name: "check", arguments: { id: "intro" } });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.content).toEqual([{ type: "text", text: "No project open — run open first" }]);
|
||||
});
|
||||
});
|
||||
44
apps/desktop/src/dapi/tools-session.ts
Normal file
@ -0,0 +1,44 @@
|
||||
/* 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 { ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
||||
import { toolJsonSchemas, tools } from "@diffusionstudio/dapi";
|
||||
import { present, toCallToolResult, toErrorResult } from "./present";
|
||||
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import type { GenericTool, ToolName } from "@diffusionstudio/dapi";
|
||||
|
||||
/** Runs one tool wherever it lives (main or renderer) and returns the handler's raw result. */
|
||||
export type ToolRunner = (tool: GenericTool, args: unknown, signal: AbortSignal) => Promise<unknown>;
|
||||
|
||||
/**
|
||||
* Serves the whole catalog on an MCP session: every tool registered with the
|
||||
* SDK, which validates arguments against the zod schema and structured
|
||||
* content against the output schema, and a `tools/list` of our own.
|
||||
*
|
||||
* The list is ours because the SDK's converts the zod schemas to JSON Schema
|
||||
* draft-07, and the validators clients run reject that dialect — Claude Code
|
||||
* fails every call on the `outputSchema` before it reaches the app. What
|
||||
* clients get instead is the same schema in 2020-12 (see `toolJsonSchemas`);
|
||||
* `tools/call` and the validation behind it stay the SDK's.
|
||||
*/
|
||||
export function serveCatalog(session: McpServer, run: ToolRunner): void {
|
||||
for (const tool of tools) {
|
||||
session.registerTool(
|
||||
tool.name,
|
||||
{ title: tool.title, description: tool.description, inputSchema: tool.input, outputSchema: tool.output },
|
||||
async (args, extra) => {
|
||||
try {
|
||||
const result = await run(tool, args, extra.signal);
|
||||
return toCallToolResult(await present(tool.name as ToolName, args, result));
|
||||
} catch (error) {
|
||||
return toErrorResult(error);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
session.server.setRequestHandler(ListToolsRequestSchema, () => ({
|
||||
tools: tools.map((tool) => ({ name: tool.name, title: tool.title, description: tool.description, ...toolJsonSchemas(tool) })),
|
||||
}));
|
||||
}
|
||||
137
apps/desktop/src/edit-types.ts
Normal file
@ -0,0 +1,137 @@
|
||||
/* 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 shapes of a source edit and its outcome: the contract between the
|
||||
// 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";
|
||||
|
||||
export type { PropValue };
|
||||
|
||||
export interface SourceContext {
|
||||
/** Absolute path of the project folder. */
|
||||
dir: string;
|
||||
/**
|
||||
* Called with the project-relative path of every file about to be written
|
||||
* and the exact text it is about to hold, so that whatever is watching the
|
||||
* folder can tell the write apart from someone else's.
|
||||
*/
|
||||
onWrite?: (file: string, text: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites props of the element named by `source` (a `SOURCE_ATTR` value),
|
||||
* and — for a `<text>` — what it says. `text` is its literal content, which is
|
||||
* its children rather than a prop and so arrives on its own; an element that
|
||||
* only says something new comes with no props at all.
|
||||
*/
|
||||
export interface SourceSet {
|
||||
kind: "set";
|
||||
source: string;
|
||||
props: Record<string, PropValue>;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds `<tag {...props} />` under the element named by `parent`, in front of
|
||||
* the child named by `before` or last. `source` is the pending name the canvas
|
||||
* knows the new element by; the write answers with the real one in `ids`.
|
||||
* A parent may itself be pending when it was inserted earlier in the same
|
||||
* write. `text`, when present, is the element's literal text content
|
||||
* (`<text>Hello</text>`); without it the element is written self-closing.
|
||||
*/
|
||||
export interface SourceInsert {
|
||||
kind: "insert";
|
||||
source: string;
|
||||
parent: string;
|
||||
tag: string;
|
||||
props: Record<string, PropValue>;
|
||||
before?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the element named by `source` under the one named by `parent`, in
|
||||
* front of the child named by `before` or last. The element travels as it was
|
||||
* written — its own text, re-indented for where it lands — so a move is the
|
||||
* one edit that does not touch what an element says, only where it says it.
|
||||
* Both ends must be in one file: an element cannot move into another module's
|
||||
* JSX any more than a project could have put it there.
|
||||
*/
|
||||
export interface SourceMove {
|
||||
kind: "move";
|
||||
source: string;
|
||||
parent: string;
|
||||
before?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the element named by `source` from the file, and with it everything
|
||||
* it contains: its children are its text, and go the way a move takes them
|
||||
* along. Addressed like a move — an unnamed element is a position, and cutting
|
||||
* text renumbers positions, so the element is found before anything is cut.
|
||||
*/
|
||||
export interface SourceRemove {
|
||||
kind: "remove";
|
||||
source: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One iteration of a loop as the canvas rendered it: for every composition
|
||||
* element of the loop body, by its source, the props it came out with and (for
|
||||
* a `<text>`) its literal content — the values that were computed from the
|
||||
* item, spelled as literals. `pending` is the name the canvas already knows
|
||||
* that iteration's copy of the element by; the write answers with the real
|
||||
* 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 }>;
|
||||
|
||||
/**
|
||||
* Replaces the `<For>`/`<Index>` around the element named by `source` with
|
||||
* one copy of its body per iteration, each spelling out what that iteration
|
||||
* rendered. Nothing that comes after this in the same write can address a
|
||||
* looped element (see `inLoop`): the loop is a recipe for elements, and a
|
||||
* change to one of them means writing them down first.
|
||||
*/
|
||||
export interface SourceUnroll {
|
||||
kind: "unroll";
|
||||
source: string;
|
||||
iterations: SourceIteration[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites the initializer of an `@inspect`-annotated top-level const (see
|
||||
* @diffusionstudio/jsx's inspect). Addressed by file and variable name — a
|
||||
* const's name is unique in its module, so no id is needed — and only written
|
||||
* when the declaration still carries the annotation and holds a literal: an
|
||||
* initializer someone rewrote into an expression is theirs again.
|
||||
*/
|
||||
export interface SourceVariable {
|
||||
kind: "variable";
|
||||
file: string;
|
||||
name: string;
|
||||
value: InspectValue;
|
||||
}
|
||||
|
||||
export type SourceEdit = SourceSet | SourceInsert | SourceMove | SourceRemove | SourceUnroll | SourceVariable;
|
||||
|
||||
export interface WriteResult {
|
||||
/** Sources that could not be written, as `id` or `id (prop)`. */
|
||||
skipped: string[];
|
||||
/**
|
||||
* Elements that earned a name in this write, as `old source id -> new one`.
|
||||
* The canvas re-stamps its entities with these, so identity does not have to
|
||||
* wait for a recompile.
|
||||
*/
|
||||
ids?: Record<string, string>;
|
||||
/**
|
||||
* The loops this write unrolled, by the `source` of the `SourceUnroll` that
|
||||
* asked. An unroll not listed here was declined, and the canvas takes its
|
||||
* loop back (see the edit writer).
|
||||
*/
|
||||
unrolled?: string[];
|
||||
error?: string;
|
||||
}
|
||||
77
apps/desktop/src/edit.test.ts
Normal file
@ -0,0 +1,77 @@
|
||||
/* 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>`);
|
||||
});
|
||||
});
|
||||
@ -4,14 +4,16 @@
|
||||
|
||||
|
||||
import { randomInt } from "node:crypto";
|
||||
import { readdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { IndentationText, Project, SyntaxKind } from "ts-morph";
|
||||
|
||||
import { ID_ATTR, INSPECT_TAG, formatSource, isCompositionTag, isLoopTag, isSerializedAssetRef, parseSource } from "@diffusionstudio/jsx";
|
||||
import { ID_ATTR, INSPECT_TAG, formatSource, isCompositionTag, isLoopTag, parseSource } from "@diffusionstudio/jsx";
|
||||
|
||||
import type { InspectValue, PropValue, SerializedAssetRef } from "@diffusionstudio/jsx";
|
||||
import { writeFileAtomic } from "./atomic";
|
||||
|
||||
import type { PropValue } from "@diffusionstudio/jsx";
|
||||
import type {
|
||||
ArrowFunction,
|
||||
FunctionExpression,
|
||||
@ -24,136 +26,18 @@ import type {
|
||||
SourceFile,
|
||||
} from "ts-morph";
|
||||
|
||||
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. */
|
||||
dir: string;
|
||||
/** Called with the project-relative path of every file written. */
|
||||
onWrite?: (file: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites props of the element named by `source` (a `SOURCE_ATTR` value),
|
||||
* and — for a `<text>` — what it says. `text` is its literal content, which is
|
||||
* its children rather than a prop and so arrives on its own; an element that
|
||||
* only says something new comes with no props at all.
|
||||
*/
|
||||
export interface SourceSet {
|
||||
kind: "set";
|
||||
source: string;
|
||||
props: Record<string, EditValue>;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds `<tag {...props} />` under the element named by `parent`, in front of
|
||||
* the child named by `before` or last. `source` is the pending name the canvas
|
||||
* knows the new element by; the write answers with the real one in `ids`.
|
||||
* A parent may itself be pending when it was inserted earlier in the same
|
||||
* write. `text`, when present, is the element's literal text content
|
||||
* (`<text>Hello</text>`); without it the element is written self-closing.
|
||||
*/
|
||||
export interface SourceInsert {
|
||||
kind: "insert";
|
||||
source: string;
|
||||
parent: string;
|
||||
tag: string;
|
||||
props: Record<string, EditValue>;
|
||||
before?: string;
|
||||
text?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the element named by `source` under the one named by `parent`, in
|
||||
* front of the child named by `before` or last. The element travels as it was
|
||||
* written — its own text, re-indented for where it lands — so a move is the
|
||||
* one edit that does not touch what an element says, only where it says it.
|
||||
* Both ends must be in one file: an element cannot move into another module's
|
||||
* JSX any more than a project could have put it there.
|
||||
*/
|
||||
export interface SourceMove {
|
||||
kind: "move";
|
||||
source: string;
|
||||
parent: string;
|
||||
before?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the element named by `source` from the file, and with it everything
|
||||
* it contains: its children are its text, and go the way a move takes them
|
||||
* along. Addressed like a move — an unnamed element is a position, and cutting
|
||||
* text renumbers positions, so the element is found before anything is cut.
|
||||
*/
|
||||
export interface SourceRemove {
|
||||
kind: "remove";
|
||||
source: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* One iteration of a loop as the canvas rendered it: for every composition
|
||||
* element of the loop body, by its source, the props it came out with and (for
|
||||
* a `<text>`) its literal content — the values that were computed from the
|
||||
* item, spelled as literals. `pending` is the name the canvas already knows
|
||||
* that iteration's copy of the element by; the write answers with the real
|
||||
* one in `ids`. The first iteration keeps the body's own names, so it carries
|
||||
* none.
|
||||
*/
|
||||
export type SourceIteration = Record<string, { props: Record<string, EditValue>; text?: string; pending?: string }>;
|
||||
|
||||
/**
|
||||
* Replaces the `<For>`/`<Index>` around the element named by `source` with
|
||||
* one copy of its body per iteration, each spelling out what that iteration
|
||||
* rendered. Nothing that comes after this in the same write can address a
|
||||
* looped element (see `inLoop`): the loop is a recipe for elements, and a
|
||||
* change to one of them means writing them down first.
|
||||
*/
|
||||
export interface SourceUnroll {
|
||||
kind: "unroll";
|
||||
source: string;
|
||||
iterations: SourceIteration[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Overwrites the initializer of an `@inspect`-annotated top-level const (see
|
||||
* @diffusionstudio/jsx's inspect). Addressed by file and variable name — a
|
||||
* const's name is unique in its module, so no id is needed — and only written
|
||||
* when the declaration still carries the annotation and holds a literal: an
|
||||
* initializer someone rewrote into an expression is theirs again.
|
||||
*/
|
||||
export interface SourceVariable {
|
||||
kind: "variable";
|
||||
file: string;
|
||||
name: string;
|
||||
value: InspectValue;
|
||||
}
|
||||
|
||||
export type SourceEdit = SourceSet | SourceInsert | SourceMove | SourceRemove | SourceUnroll | SourceVariable;
|
||||
|
||||
export interface WriteResult {
|
||||
/** Sources that could not be written, as `id` or `id (prop)`. */
|
||||
skipped: string[];
|
||||
/**
|
||||
* Elements that earned a name in this write, as `old source id -> new one`.
|
||||
* The canvas re-stamps its entities with these, so identity does not have to
|
||||
* wait for a recompile.
|
||||
*/
|
||||
ids?: Record<string, string>;
|
||||
/**
|
||||
* The loops this write unrolled, by the `source` of the `SourceUnroll` that
|
||||
* asked. An unroll not listed here was declined, and the canvas takes its
|
||||
* loop back (see the edit writer).
|
||||
*/
|
||||
unrolled?: string[];
|
||||
error?: string;
|
||||
}
|
||||
export type * from "./edit-types";
|
||||
import type {
|
||||
SourceContext,
|
||||
SourceEdit,
|
||||
SourceInsert,
|
||||
SourceIteration,
|
||||
SourceMove,
|
||||
SourceRemove,
|
||||
SourceUnroll,
|
||||
SourceVariable,
|
||||
WriteResult,
|
||||
} from "./edit-types";
|
||||
|
||||
/** The opening half of a JSX element — where its attributes live. */
|
||||
type JsxTag = JsxOpeningElement | JsxSelfClosingElement;
|
||||
@ -266,29 +150,14 @@ const initializerText = (value: PropValue): string =>
|
||||
? `"${value}"`
|
||||
: `{${literalText(value)}}`;
|
||||
|
||||
/** A declaration's wire form as the `generate.*` call that reproduces it. */
|
||||
function generateCallText(ref: SerializedAssetRef): string {
|
||||
const { type, ...options } = ref.$generate;
|
||||
return `generate.${type}(${literalText(options as Record<string, PropValue>)})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. A declaration is spelled as its `generate.*`
|
||||
* call — the caller makes sure `generate` is imported (see
|
||||
* `ensureGenerateImport`).
|
||||
* boolean prop's false reads as.
|
||||
*/
|
||||
function setProp(tag: JsxTag, name: string, value: EditValue): void {
|
||||
function setProp(tag: JsxTag, name: string, value: PropValue): void {
|
||||
const attribute = attributeOf(tag, name);
|
||||
|
||||
if (isSerializedAssetRef(value)) {
|
||||
const initializer = `{${generateCallText(value)}}`;
|
||||
if (attribute) attribute.setInitializer(initializer);
|
||||
else tag.addAttribute({ name, initializer });
|
||||
return;
|
||||
}
|
||||
|
||||
if (value === true) {
|
||||
if (attribute) attribute.removeInitializer();
|
||||
else tag.addAttribute({ name });
|
||||
@ -304,40 +173,6 @@ function setProp(tag: JsxTag, name: string, value: EditValue): void {
|
||||
else tag.addAttribute({ name, initializer: initializerText(value) });
|
||||
}
|
||||
|
||||
/** Where `generate` comes from — the module every project authors against. */
|
||||
const GENERATE_MODULE = "@diffusionstudio/jsx";
|
||||
|
||||
/**
|
||||
* Makes sure `generate` is in scope once a declaration has been spelled into
|
||||
* the file: added to the module's existing import, or as an import of its 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 ensureGenerateImport(sourceFile: SourceFile): void {
|
||||
const declarations = sourceFile.getImportDeclarations();
|
||||
const importable = declarations.find(
|
||||
(declaration) =>
|
||||
declaration.getModuleSpecifierValue() === GENERATE_MODULE &&
|
||||
!declaration.isTypeOnly() &&
|
||||
!declaration.getNamespaceImport(),
|
||||
);
|
||||
|
||||
if (importable) {
|
||||
const named = importable.getNamedImports();
|
||||
if (named.some((specifier) => specifier.getName() === "generate" && !specifier.getAliasNode())) return;
|
||||
importable.addNamedImport("generate");
|
||||
return;
|
||||
}
|
||||
|
||||
const statement = `import { generate } from "${GENERATE_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
|
||||
@ -349,8 +184,10 @@ function jsxText(text: string): string {
|
||||
|
||||
/**
|
||||
* Replaces what an element says between its tags; a self-closing one is opened
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
function setText(sourceFile: SourceFile, tag: JsxTag, text: string): void {
|
||||
const element = elementOf(tag);
|
||||
@ -362,7 +199,44 @@ function setText(sourceFile: SourceFile, tag: JsxTag, text: string): void {
|
||||
return;
|
||||
}
|
||||
|
||||
sourceFile.replaceText([element.getOpeningElement().getEnd(), element.getClosingElement().getStart()], content);
|
||||
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];
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@ -575,42 +449,11 @@ function isLiteral(node: Node): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A `generate.*` call over a literal spec: what the writer spells a
|
||||
* declaration as, and so an initializer it may also overwrite. One whose
|
||||
* argument computes anything is authored reactivity, like any expression.
|
||||
*/
|
||||
function isGenerateCall(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 (callee.getExpression().getText() !== "generate") 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) || isGenerateCall(expression));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Files
|
||||
|
||||
/** Every project source file, project-relative and `/`-separated. */
|
||||
async function sourceFiles(dir: string, prefix = ""): Promise<string[]> {
|
||||
export async function sourceFiles(dir: string, prefix = ""): Promise<string[]> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await readdir(prefix ? join(dir, ...prefix.split("/")) : dir, { withFileTypes: true });
|
||||
@ -731,9 +574,11 @@ class SourceWriter {
|
||||
open.text = text;
|
||||
|
||||
// Claimed before the write lands: a watcher must never see this change
|
||||
// arrive without knowing whose it was.
|
||||
this.context.onWrite?.(path);
|
||||
await writeFile(absolute(this.context.dir, path), text, "utf8");
|
||||
// arrive without knowing whose it was, and what says whose it is are the
|
||||
// bytes themselves — so they go with the claim. Written whole, because
|
||||
// the same watcher reads the file straight back.
|
||||
this.context.onWrite?.(path, text);
|
||||
await writeFileAtomic(absolute(this.context.dir, path), text);
|
||||
}
|
||||
}
|
||||
|
||||
@ -779,10 +624,10 @@ class SourceWriter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
public async applyEdits(edits: SourceEdit[]): Promise<WriteResult> {
|
||||
const skipped: string[] = [];
|
||||
@ -911,14 +756,11 @@ class SourceWriter {
|
||||
break;
|
||||
}
|
||||
|
||||
const attribute = attributeOf(tag, name);
|
||||
if (attribute && !isWritable(attribute)) {
|
||||
skipped.push(`${edit.source} (${name})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 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.
|
||||
setProp(tag, name, value);
|
||||
if (isSerializedAssetRef(value)) ensureGenerateImport(sourceFile);
|
||||
wrote = true;
|
||||
}
|
||||
|
||||
@ -956,8 +798,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 — an expression there is authored
|
||||
* reactivity again, the same rule `isWritable` applies to a prop.
|
||||
* its initializer is not a literal anymore: the annotation promises the
|
||||
* inspector a value, and an expression there is no longer one.
|
||||
*/
|
||||
private setVariable(sourceFile: SourceFile, edit: SourceVariable): boolean {
|
||||
for (const statement of sourceFile.getVariableStatements()) {
|
||||
@ -1015,7 +857,6 @@ 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)) ensureGenerateImport(sourceFile);
|
||||
}
|
||||
ids[edit.source] = formatSource(file, id);
|
||||
return true;
|
||||
@ -1255,7 +1096,6 @@ class SourceWriter {
|
||||
}
|
||||
for (const [name, value] of Object.entries(record.props)) {
|
||||
setProp(found(), name, value);
|
||||
if (isSerializedAssetRef(value)) ensureGenerateImport(sourceFile);
|
||||
}
|
||||
|
||||
const element = elementOf(found());
|
||||
|
||||
64
apps/desktop/src/editors.ts
Normal file
@ -0,0 +1,64 @@
|
||||
/* 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();
|
||||
}
|
||||
136
apps/desktop/src/legacy-generations.test.ts
Normal file
@ -0,0 +1,136 @@
|
||||
/* 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([]);
|
||||
});
|
||||
});
|
||||
509
apps/desktop/src/legacy-generations.ts
Normal file
@ -0,0 +1,509 @@
|
||||
/* 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);
|
||||
}
|
||||
}
|
||||
@ -7,10 +7,13 @@
|
||||
// through these via an envelope carrying the logical MAIN_CHANNELS name and
|
||||
// (for requests) a UUID for correlation.
|
||||
//
|
||||
// CLI traffic uses a separate wire pair (CLI_WIRE in @diffusionstudio/cli/protocol);
|
||||
// main forwards it opaquely without inspecting channel names.
|
||||
import type { LogEntry, ScreenshotResult } from "@diffusionstudio/cli/protocol";
|
||||
import type { SourceEdit, WriteResult } from "./edit";
|
||||
// Tool calls from the MCP server use their own wire (DAPI_WIRE in
|
||||
// @diffusionstudio/dapi), in the other direction: main asks, the renderer answers.
|
||||
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",
|
||||
@ -23,34 +26,39 @@ export type MainWireChannel = (typeof MAIN_WIRE)[keyof typeof MAIN_WIRE];
|
||||
// Logical channels. Two categories:
|
||||
// • Renderer→Main requests (request + response)
|
||||
// • Main→Renderer events (push, no response)
|
||||
// Renderer-state queries used to live here; they now answer CLI requests
|
||||
// directly via the CLI bridge.
|
||||
// Tool calls are not here: they arrive from main over DAPI_WIRE and are
|
||||
// answered by the renderer's handlers (apps/web/src/dapi).
|
||||
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",
|
||||
CLI_IS_INSTALLED: "cli:is-installed",
|
||||
CLI_INSTALL: "cli:install",
|
||||
SKILLS_IS_INSTALLED: "skills:is-installed",
|
||||
SKILLS_INSTALL: "skills:install",
|
||||
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",
|
||||
HEADLESS_GET_MODE: "headless:get-mode",
|
||||
LOGS_GET: "logs:get",
|
||||
PROJECTS_PICK_ROOT: "projects:pick-root",
|
||||
PROJECTS_DEFAULT_ROOT: "projects:default-root",
|
||||
PROJECTS_LIST: "projects:list",
|
||||
PROJECTS_PICK_FOLDER: "projects:pick-folder",
|
||||
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",
|
||||
@ -66,19 +74,24 @@ export const MAIN_CHANNELS = {
|
||||
PROJECTS_FS_STAT: "projects:fs-stat",
|
||||
PROJECTS_FS_REMOVE: "projects:fs-remove",
|
||||
PROJECTS_FS_REAL_PATH: "projects:fs-real-path",
|
||||
AGENT_CHAT_ENDPOINT: "agent-chat:endpoint",
|
||||
MCP_STATUS: "mcp:status",
|
||||
MCP_APPLY: "mcp:apply",
|
||||
CLI_STATUS: "cli:status",
|
||||
CLI_INSTALL: "cli:install",
|
||||
CLI_UNINSTALL: "cli:uninstall",
|
||||
|
||||
// Main→Renderer events
|
||||
AUTH_CALLBACK: "auth:callback",
|
||||
CHECKOUT_CALLBACK: "checkout:callback",
|
||||
WINDOW_FULLSCREEN_CHANGE: "window:fullscreen-change",
|
||||
HEADLESS_MODE: "headless:mode",
|
||||
PROJECTS_CHANGED: "projects:changed",
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* A project folder under the projects root: a real npm package with a JSX
|
||||
* entry. Its package.json is the project record: `projectId` is what the
|
||||
* project is, `displayName` the human name, `main` the entry file.
|
||||
* A project folder, wherever it lives: a real npm package with a JSX entry.
|
||||
* Its package.json is the project record: `projectId` is what the project
|
||||
* is, `displayName` the human name, `main` the entry file.
|
||||
*/
|
||||
export type ProjectInfo = {
|
||||
/**
|
||||
@ -87,7 +100,7 @@ export type ProjectInfo = {
|
||||
* since — `PROJECTS_RESOLVE` is what gives one out.
|
||||
*/
|
||||
id: string;
|
||||
/** Folder name. Renaming the project moves it, so it is not the identity. */
|
||||
/** Folder name. The user can move or rename it, so it is not the identity. */
|
||||
name: string;
|
||||
/** Human name from package.json `displayName` (falls back to the folder name). */
|
||||
displayName: string;
|
||||
@ -99,44 +112,104 @@ 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 =
|
||||
| { ok: true; code: string }
|
||||
| { ok: false; error: string };
|
||||
{ ok: true; code: string } | { ok: false; error: string };
|
||||
|
||||
// Outcome of linking the bundled dapi CLI into PATH. "cancelled" means the
|
||||
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
|
||||
// agents that need the bundled `dapi` binary — why this build cannot
|
||||
// connect it (null when it can).
|
||||
export type McpAgentStatus = {
|
||||
id: AgentId;
|
||||
label: string;
|
||||
detected: boolean;
|
||||
connected: boolean;
|
||||
/** Absolute path of the config file the entry goes into. */
|
||||
config: string;
|
||||
unavailable: string | null;
|
||||
};
|
||||
|
||||
/** `url` is the HTTP endpoint any other agent can be pointed at by hand. */
|
||||
export type McpStatus = { url: string; agents: McpAgentStatus[] };
|
||||
|
||||
export type McpApplyRequest = { add: AgentId[]; remove: AgentId[] };
|
||||
|
||||
// Per agent: written, taken out, or left as it was with the reason.
|
||||
export type McpApplyResult = {
|
||||
added: AgentId[];
|
||||
removed: AgentId[];
|
||||
failures: { id: AgentId; error: string }[];
|
||||
};
|
||||
|
||||
// Where the `diffusion` 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).
|
||||
export type CliStatus = {
|
||||
installed: boolean;
|
||||
path: string | null;
|
||||
managed: boolean;
|
||||
available: boolean;
|
||||
};
|
||||
|
||||
// Outcome of linking the bundled diffusion CLI into PATH. "cancelled" means the
|
||||
// user dismissed the macOS admin prompt — not an error, not installed.
|
||||
export type CliInstallResult =
|
||||
| { status: "installed" }
|
||||
| { status: "cancelled" }
|
||||
| { status: "error"; error: string };
|
||||
|
||||
// Outcome of symlinking the bundled skills into the agent skill directories.
|
||||
export type SkillsInstallResult =
|
||||
| { status: "installed" }
|
||||
// Outcome of taking the symlink back out. "absent" means there was none to
|
||||
// remove; "cancelled" that the admin prompt was dismissed and it stays.
|
||||
export type CliUninstallResult =
|
||||
| { status: "removed" }
|
||||
| { status: "absent" }
|
||||
| { status: "cancelled" }
|
||||
| { status: "error"; error: string };
|
||||
|
||||
export type { SourceEdit, WriteResult };
|
||||
|
||||
export type MainChannel = (typeof MAIN_CHANNELS)[keyof typeof MAIN_CHANNELS];
|
||||
|
||||
// Events fed by a `diffusion://` deep link. Main routes each link to exactly
|
||||
// one of these by its host, so auth and checkout never consume each other's.
|
||||
export type DeepLinkChannel =
|
||||
| typeof MAIN_CHANNELS.AUTH_CALLBACK
|
||||
| typeof MAIN_CHANNELS.CHECKOUT_CALLBACK;
|
||||
typeof MAIN_CHANNELS.AUTH_CALLBACK | typeof MAIN_CHANNELS.CHECKOUT_CALLBACK;
|
||||
|
||||
export type MainRequestMap = {
|
||||
[MAIN_CHANNELS.APP_OPEN_EXTERNAL]: { request: { url: string }; response: void };
|
||||
[MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK]: { request: void; response: string | null };
|
||||
[MAIN_CHANNELS.CHECKOUT_GET_PENDING_CALLBACK]: { request: void; response: string | null };
|
||||
[MAIN_CHANNELS.CLI_IS_INSTALLED]: { request: void; response: boolean };
|
||||
[MAIN_CHANNELS.CLI_INSTALL]: { request: void; response: CliInstallResult };
|
||||
[MAIN_CHANNELS.SKILLS_IS_INSTALLED]: { request: void; response: boolean };
|
||||
[MAIN_CHANNELS.SKILLS_INSTALL]: { request: void; response: SkillsInstallResult };
|
||||
[MAIN_CHANNELS.APP_OPEN_EXTERNAL]: {
|
||||
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;
|
||||
};
|
||||
[MAIN_CHANNELS.CHECKOUT_GET_PENDING_CALLBACK]: {
|
||||
request: void;
|
||||
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;
|
||||
@ -158,51 +231,140 @@ export type MainRequestMap = {
|
||||
response: void;
|
||||
};
|
||||
// Reveals a file or folder in the OS file manager (Finder on macOS).
|
||||
[MAIN_CHANNELS.APP_SHOW_IN_FOLDER]: { request: { path: string }; response: void };
|
||||
[MAIN_CHANNELS.HEADLESS_GET_MODE]: { request: void; response: boolean };
|
||||
[MAIN_CHANNELS.APP_SHOW_IN_FOLDER]: {
|
||||
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_DEFAULT_ROOT]: { request: void; response: string | null };
|
||||
[MAIN_CHANNELS.PROJECTS_LIST]: { request: { root: string }; response: ProjectInfo[] };
|
||||
[MAIN_CHANNELS.PROJECTS_GET]: { request: { dir: string }; response: ProjectInfo | null };
|
||||
[MAIN_CHANNELS.PROJECTS_INIT]: { request: { dir: string }; response: ProjectInfo };
|
||||
[MAIN_CHANNELS.PROJECTS_RESOLVE]: {
|
||||
request: { root: string; ref: string };
|
||||
[MAIN_CHANNELS.PROJECTS_PICK_FOLDER]: {
|
||||
request: void;
|
||||
response: string | null;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_GET]: {
|
||||
request: { dir: string };
|
||||
response: ProjectInfo | null;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_CREATE]: {
|
||||
request: { root: string; displayName: string };
|
||||
[MAIN_CHANNELS.PROJECTS_INIT]: {
|
||||
request: { dir: string };
|
||||
response: ProjectInfo;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_RESOLVE]: {
|
||||
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 };
|
||||
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;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_DUPLICATE]: { request: { dir: string }; response: ProjectInfo };
|
||||
[MAIN_CHANNELS.PROJECTS_DUPLICATE]: {
|
||||
request: { dir: string };
|
||||
response: ProjectInfo;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_DELETE]: { request: { dir: string }; response: void };
|
||||
[MAIN_CHANNELS.PROJECTS_COMPILE]: { request: { dir: string }; response: CompileResult };
|
||||
[MAIN_CHANNELS.PROJECTS_COMPILE]: {
|
||||
request: { dir: string };
|
||||
response: CompileResult;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_WRITE]: {
|
||||
request: { dir: string; edits: SourceEdit[] };
|
||||
response: WriteResult;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_WATCH]: { request: { dir: string }; response: void };
|
||||
[MAIN_CHANNELS.PROJECTS_UNWATCH]: { request: { dir: string }; response: void };
|
||||
[MAIN_CHANNELS.PROJECTS_UNWATCH]: {
|
||||
request: { dir: string };
|
||||
response: void;
|
||||
};
|
||||
// The asset manifest (`assets.yml`) as plain data; null when there is none.
|
||||
[MAIN_CHANNELS.PROJECTS_MANIFEST_READ]: { request: { dir: string }; response: unknown };
|
||||
[MAIN_CHANNELS.PROJECTS_MANIFEST_WRITE]: { request: { dir: string; manifest: unknown }; response: void };
|
||||
[MAIN_CHANNELS.PROJECTS_MANIFEST_READ]: {
|
||||
request: { dir: string };
|
||||
response: unknown;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_MANIFEST_WRITE]: {
|
||||
request: { dir: string; manifest: unknown };
|
||||
response: void;
|
||||
};
|
||||
// The project's config: the `diffusion` field of its package.json, as
|
||||
// parsed (null when absent). The renderer owns its shape; see
|
||||
// `engine/project-config` in the web app.
|
||||
[MAIN_CHANNELS.PROJECTS_CONFIG_READ]: { request: { dir: string }; response: unknown };
|
||||
[MAIN_CHANNELS.PROJECTS_CONFIG_WRITE]: { request: { dir: string; config: unknown }; response: void };
|
||||
[MAIN_CHANNELS.PROJECTS_CONFIG_READ]: {
|
||||
request: { dir: string };
|
||||
response: unknown;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_CONFIG_WRITE]: {
|
||||
request: { dir: string; config: unknown };
|
||||
response: void;
|
||||
};
|
||||
// Project file system, for the asset library. `source` is project-relative
|
||||
// or absolute; `path` is always project-relative. Writes stream through the
|
||||
// FILE_WRITE_* channels (which create parent directories).
|
||||
[MAIN_CHANNELS.PROJECTS_FS_LIST]: { request: { dir: string; source: string }; response: FsEntry[] };
|
||||
[MAIN_CHANNELS.PROJECTS_FS_STAT]: { request: { dir: string; source: string }; response: FsStat | null };
|
||||
[MAIN_CHANNELS.PROJECTS_FS_REMOVE]: { request: { dir: string; path: string }; response: void };
|
||||
[MAIN_CHANNELS.PROJECTS_FS_REAL_PATH]: { request: { dir: string; source: string }; response: string | null };
|
||||
[MAIN_CHANNELS.PROJECTS_FS_LIST]: {
|
||||
request: { dir: string; source: string };
|
||||
response: FsEntry[];
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_FS_STAT]: {
|
||||
request: { dir: string; source: string };
|
||||
response: FsStat | null;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_FS_REMOVE]: {
|
||||
request: { dir: string; path: string };
|
||||
response: void;
|
||||
};
|
||||
[MAIN_CHANNELS.PROJECTS_FS_REAL_PATH]: {
|
||||
request: { dir: string; source: string };
|
||||
response: string | null;
|
||||
};
|
||||
// Where the agent chat host listens (`ws://127.0.0.1:PORT/?token=…`); null
|
||||
// while it is starting or restarting. The only desktop IPC the chat uses.
|
||||
[MAIN_CHANNELS.AGENT_CHAT_ENDPOINT]: {
|
||||
request: void;
|
||||
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
|
||||
// calls put the macOS admin prompt on screen.
|
||||
[MAIN_CHANNELS.MCP_STATUS]: { request: void; response: McpStatus };
|
||||
[MAIN_CHANNELS.MCP_APPLY]: { request: McpApplyRequest; response: McpApplyResult };
|
||||
[MAIN_CHANNELS.CLI_STATUS]: { request: void; response: CliStatus };
|
||||
[MAIN_CHANNELS.CLI_INSTALL]: { request: void; response: CliInstallResult };
|
||||
[MAIN_CHANNELS.CLI_UNINSTALL]: { request: void; response: CliUninstallResult };
|
||||
};
|
||||
|
||||
export type FsEntry = {
|
||||
@ -220,7 +382,6 @@ export type MainEventMap = {
|
||||
[MAIN_CHANNELS.AUTH_CALLBACK]: { url: string };
|
||||
[MAIN_CHANNELS.CHECKOUT_CALLBACK]: { url: string };
|
||||
[MAIN_CHANNELS.WINDOW_FULLSCREEN_CHANGE]: { fullscreen: boolean };
|
||||
[MAIN_CHANNELS.HEADLESS_MODE]: { active: boolean };
|
||||
// A file inside a watched project folder changed (path relative to `dir`).
|
||||
[MAIN_CHANNELS.PROJECTS_CHANGED]: { dir: string; path: string };
|
||||
};
|
||||
|
||||
@ -4,33 +4,46 @@
|
||||
|
||||
import { app, BrowserWindow, nativeImage, session, shell } from "electron";
|
||||
import { dirname, join } from "node:path";
|
||||
import { mkdir, open, unlink } from "node:fs/promises";
|
||||
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 { updateElectronApp } from "update-electron-app";
|
||||
import { startCliServer, stopCliServer, isHeadless } from "./cli-server";
|
||||
import { installCli, isCliInstalled } from "./cli-install";
|
||||
import { healSkillsLinks, installSkills, isSkillsInstalled } from "./skills-install";
|
||||
import { trackInstall } from "./analytics";
|
||||
import type { IUpdateInfo } from "update-electron-app";
|
||||
import { makeUserNotifier, 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 { applyMcp, healMcpRegistrations, mcpStatus } from "./mcp-install";
|
||||
import { configureAnalytics, countCanvasEdits, startAnalytics, track } 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,
|
||||
listProjects,
|
||||
pickRoot,
|
||||
pickFolder,
|
||||
pickSaveLocation,
|
||||
renameProject,
|
||||
resolveProject,
|
||||
saveProject,
|
||||
moveProject,
|
||||
unwatchAll,
|
||||
listEntries,
|
||||
realPathEntry,
|
||||
markSelfWriteAbsolute,
|
||||
noteContent,
|
||||
noteRenamed,
|
||||
readConfig,
|
||||
readManifest,
|
||||
removeEntry,
|
||||
@ -42,12 +55,27 @@ import {
|
||||
writeProject,
|
||||
} from "./projects";
|
||||
import type { DeepLinkChannel } from "./main-channels";
|
||||
import type { LogEntry } from "@diffusionstudio/cli/protocol";
|
||||
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");
|
||||
@ -79,13 +107,55 @@ function applyBackdrop() {
|
||||
setNativeBackdrop(mainWindow.getNativeWindowHandle(), blur, red, green, blue, alpha);
|
||||
}
|
||||
|
||||
if (app.isPackaged && !process.argv.includes("--hidden")) {
|
||||
updateElectronApp({ repo: "diffusionstudio/editor" });
|
||||
function setColorMode(mode: "dark" | "light") {
|
||||
if (process.platform === "darwin" || !mainWindow || mainWindow.isDestroyed()) return;
|
||||
mainWindow.setTitleBarOverlay({ ...WINDOWS_OVERLAY_COLORS[mode], height: WINDOWS_OVERLAY_HEIGHT });
|
||||
}
|
||||
|
||||
const openWrites = new Map<string, { handle: FileHandle; path: string }>();
|
||||
// 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();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
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.
|
||||
@ -97,6 +167,32 @@ const pendingDeepLinks = new Map<DeepLinkChannel, string>();
|
||||
const LOG_BUFFER_MAX = 2000;
|
||||
const logBuffer: LogEntry[] = [];
|
||||
|
||||
// The docs the MCP instructions point agents at: staged into the bundle by
|
||||
// scripts/stage-docs.mjs (Contents/Resources/docs) when packaged; the repo's
|
||||
// own `docs/` in development, so edits show up without a staging step. Null
|
||||
// when neither exists.
|
||||
function docsDir(): string | null {
|
||||
const dir = app.isPackaged ? join(process.resourcesPath, "docs") : join(app.getAppPath(), "..", "..", "docs");
|
||||
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.
|
||||
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),
|
||||
});
|
||||
|
||||
function pushLog(level: LogEntry["level"], message: string, source: string) {
|
||||
logBuffer.push({ ts: Date.now(), level, message, source });
|
||||
if (logBuffer.length > LOG_BUFFER_MAX) logBuffer.shift();
|
||||
@ -176,20 +272,38 @@ async function setFileInputFiles(selector: string, absolutePath: string) {
|
||||
});
|
||||
}
|
||||
|
||||
function createWindow(show = true) {
|
||||
mainWindow = new BrowserWindow({
|
||||
// The main window, not shown: WindowHost decides when it is.
|
||||
function createWindow(): BrowserWindow {
|
||||
|
||||
const options: Electron.BrowserWindowConstructorOptions = {
|
||||
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);
|
||||
|
||||
@ -199,10 +313,6 @@ function createWindow(show = true) {
|
||||
mainWindow.once("ready-to-show", () => {
|
||||
applyCornerRadius(MACOS_CORNER_RADIUS);
|
||||
applyBackdrop();
|
||||
|
||||
if (show) {
|
||||
mainWindow?.show();
|
||||
}
|
||||
});
|
||||
|
||||
mainWindow.on("show", () => {
|
||||
@ -220,6 +330,7 @@ function createWindow(show = true) {
|
||||
});
|
||||
mainWindow.on("closed", () => {
|
||||
mainWindow = null;
|
||||
unwatchAll();
|
||||
});
|
||||
|
||||
if (!app.isPackaged) {
|
||||
@ -227,6 +338,8 @@ function createWindow(show = true) {
|
||||
} else {
|
||||
mainWindow.loadFile(join(app.getAppPath(), "web", "index.html"));
|
||||
}
|
||||
|
||||
return mainWindow;
|
||||
}
|
||||
|
||||
if (process.defaultApp && process.argv.length >= 2) {
|
||||
@ -237,33 +350,34 @@ if (process.defaultApp && process.argv.length >= 2) {
|
||||
app.setAsDefaultProtocolClient(AUTH_PROTOCOL);
|
||||
}
|
||||
|
||||
if (app.requestSingleInstanceLock()) {
|
||||
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();
|
||||
}
|
||||
|
||||
app.on("second-instance", (_event, argv) => {
|
||||
const url = findProtocolUrl(argv);
|
||||
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);
|
||||
if (url) {
|
||||
deliverDeepLink(url);
|
||||
}
|
||||
if (!isHiddenLaunch(argv)) {
|
||||
windows.show();
|
||||
}
|
||||
});
|
||||
|
||||
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.CLI_IS_INSTALLED, () => isCliInstalled());
|
||||
mainBridge.handle(MAIN_CHANNELS.CLI_INSTALL, () => installCli());
|
||||
mainBridge.handle(MAIN_CHANNELS.SKILLS_IS_INSTALLED, () => isSkillsInstalled());
|
||||
mainBridge.handle(MAIN_CHANNELS.SKILLS_INSTALL, () => installSkills());
|
||||
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),
|
||||
);
|
||||
@ -271,32 +385,59 @@ if (app.requestSingleInstanceLock()) {
|
||||
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 });
|
||||
const { width, height } = image.getSize();
|
||||
return { base64: image.toPNG().toString("base64"), width, height };
|
||||
const png = image.toPNG();
|
||||
// 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.HEADLESS_GET_MODE, () => isHeadless());
|
||||
mainBridge.handle(MAIN_CHANNELS.CLIPBOARD_PATHS, () => clipboardPaths());
|
||||
mainBridge.handle(MAIN_CHANNELS.LOGS_GET, () => logBuffer);
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_ROOT, () => pickRoot(mainWindow));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_DEFAULT_ROOT, () => defaultRoot(mainWindow));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_LIST, ({ root }) => listProjects(root));
|
||||
mainBridge.handle(MAIN_CHANNELS.AGENT_CHAT_ENDPOINT, () => agentChatEndpoint());
|
||||
mainBridge.handle(MAIN_CHANNELS.MCP_STATUS, () => mcpStatus());
|
||||
mainBridge.handle(MAIN_CHANNELS.MCP_APPLY, (request) => applyMcp(request));
|
||||
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_FOLDER, () => pickFolder(mainWindow));
|
||||
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, ({ root, ref }) => resolveProject(root, ref));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, ({ root, displayName }) =>
|
||||
createProject(root, displayName),
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_RESOLVE, ({ dir }) => resolveProject(dir));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_FIND_MOVED, ({ dir, id }) => findMovedProject(dir, id));
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_ASK_MISSING, ({ displayName, dir }) =>
|
||||
askAboutMissingProject(mainWindow, displayName, dir),
|
||||
);
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_CREATE, () => createProject());
|
||||
mainBridge.handle(MAIN_CHANNELS.PROJECTS_PICK_SAVE, ({ dir, 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));
|
||||
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 }) => 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_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_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));
|
||||
@ -311,17 +452,29 @@ if (app.requestSingleInstanceLock()) {
|
||||
|
||||
mainBridge.handle(MAIN_CHANNELS.FILE_WRITE_OPEN, async ({ path, exclusive }) => {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
markSelfWriteAbsolute(path);
|
||||
const handle = await open(path, exclusive ? "wx" : "w");
|
||||
|
||||
// `exclusive` means the name must be free, so it is taken now rather than
|
||||
// at the rename below — the empty file that reserves it is renamed over
|
||||
// when the write finishes, and removed when it is abandoned.
|
||||
if (exclusive) {
|
||||
noteContent(path, "");
|
||||
await (await open(path, "wx")).close();
|
||||
}
|
||||
|
||||
// The bytes go to a temp file beside the destination and are renamed into
|
||||
// place once they are whole. Nothing ever sees half an asset — not the
|
||||
// watcher, not a scan of the library, not an import — so there is no
|
||||
// window anyone has to be kept out of.
|
||||
const temp = tempPathFor(path);
|
||||
const handle = await open(temp, "wx");
|
||||
const id = randomUUID();
|
||||
openWrites.set(id, { handle, path });
|
||||
openWrites.set(id, { handle, path, temp, reserved: exclusive === true });
|
||||
return { id };
|
||||
});
|
||||
|
||||
mainBridge.handle(MAIN_CHANNELS.FILE_WRITE_CHUNK, async ({ id, data, position }) => {
|
||||
const entry = openWrites.get(id);
|
||||
if (!entry) throw new Error(`No open file for write id ${id}`);
|
||||
markSelfWriteAbsolute(entry.path);
|
||||
await entry.handle.write(data, 0, data.byteLength, position);
|
||||
});
|
||||
|
||||
@ -329,11 +482,21 @@ if (app.requestSingleInstanceLock()) {
|
||||
const entry = openWrites.get(id);
|
||||
if (!entry) return;
|
||||
openWrites.delete(id);
|
||||
markSelfWriteAbsolute(entry.path);
|
||||
await entry.handle.close();
|
||||
try {
|
||||
await entry.handle.close();
|
||||
// Claimed before the rename, which is the first and only moment the
|
||||
// destination changes (see `noteRenamed`).
|
||||
await noteRenamed(entry.temp, entry.path);
|
||||
await rename(entry.temp, entry.path);
|
||||
} catch (error) {
|
||||
await unlink(entry.temp).catch(() => { });
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
// Abort: close the fd and delete the partial file (cancel / error cleanup).
|
||||
// Abort: close the fd and drop the temp file (cancel / error cleanup). The
|
||||
// destination is left alone — an abandoned write never reached it — bar the
|
||||
// name an `exclusive` open reserved, which is given back.
|
||||
mainBridge.handle(MAIN_CHANNELS.FILE_WRITE_ABORT, async ({ id }) => {
|
||||
const entry = openWrites.get(id);
|
||||
if (!entry) return;
|
||||
@ -341,7 +504,11 @@ if (app.requestSingleInstanceLock()) {
|
||||
try {
|
||||
await entry.handle.close();
|
||||
} finally {
|
||||
await unlink(entry.path).catch(() => { });
|
||||
await unlink(entry.temp).catch(() => { });
|
||||
if (entry.reserved) {
|
||||
noteContent(entry.path, null);
|
||||
await unlink(entry.path).catch(() => { });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@ -359,35 +526,39 @@ if (app.requestSingleInstanceLock()) {
|
||||
const url = findProtocolUrl(process.argv);
|
||||
if (url) deliverDeepLink(url);
|
||||
|
||||
startCliServer();
|
||||
healSkillsLinks();
|
||||
trackInstall();
|
||||
createWindow(!isHiddenLaunch(process.argv));
|
||||
dapi.start();
|
||||
// The chat's sessions get the MCP server by URL.
|
||||
dapi.mcpUrl().then((url) =>
|
||||
configureAgentChat({
|
||||
dataDir: join(app.getPath("userData"), "agent-chat"),
|
||||
mcpUrl: url,
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
app.on("before-quit", () => {
|
||||
unwatchAll();
|
||||
stopCliServer();
|
||||
stopAgentChat();
|
||||
dapi.stop();
|
||||
tray.destroy();
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
app.quit();
|
||||
}
|
||||
});
|
||||
// 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("activate", () => {
|
||||
if (!mainWindow || mainWindow.isDestroyed()) {
|
||||
createWindow();
|
||||
return;
|
||||
}
|
||||
|
||||
if (mainWindow.isMinimized()) {
|
||||
mainWindow.restore();
|
||||
}
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
});
|
||||
// The Dock icon, or launching the app again while it runs.
|
||||
app.on("activate", () => windows.show());
|
||||
} else {
|
||||
app.quit();
|
||||
}
|
||||
|
||||
203
apps/desktop/src/mcp-config.test.ts
Normal file
@ -0,0 +1,203 @@
|
||||
/* 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 {
|
||||
AGENT_TARGETS,
|
||||
agentTarget,
|
||||
needsBinary,
|
||||
readServer,
|
||||
removeServer,
|
||||
runsOurProxy,
|
||||
sameCommand,
|
||||
upsertServer,
|
||||
} from "./mcp-config";
|
||||
|
||||
const spec = {
|
||||
url: "http://127.0.0.1:3274/mcp",
|
||||
command: "/Applications/Diffusion Studio.app/Contents/Resources/cli/bin/dapi",
|
||||
args: ["mcp"],
|
||||
};
|
||||
|
||||
describe("per-agent entries", () => {
|
||||
it("spells the URL the way each agent expects", () => {
|
||||
expect(agentTarget("claude-code").entry(spec)).toEqual({ type: "http", url: spec.url });
|
||||
expect(agentTarget("cursor").entry(spec)).toEqual({ url: spec.url });
|
||||
expect(agentTarget("vscode").entry(spec)).toEqual({ type: "http", url: spec.url });
|
||||
expect(agentTarget("codex").entry(spec)).toEqual({ url: spec.url });
|
||||
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", () => {
|
||||
expect(agentTarget("claude-desktop").entry(spec)).toEqual({ command: spec.command, args: ["mcp"] });
|
||||
expect(AGENT_TARGETS.filter(needsBinary).map((t) => t.id)).toEqual(["claude-desktop"]);
|
||||
});
|
||||
|
||||
it("has a unique id per agent", () => {
|
||||
expect(new Set(AGENT_TARGETS.map((t) => t.id)).size).toBe(AGENT_TARGETS.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe("json configs", () => {
|
||||
it("creates the file from nothing", () => {
|
||||
const text = upsertServer(null, "mcpServers", { type: "http", url: spec.url });
|
||||
expect(JSON.parse(text)).toEqual({ mcpServers: { diffusion: { type: "http", url: spec.url } } });
|
||||
expect(text.endsWith("\n")).toBe(true);
|
||||
});
|
||||
|
||||
it("uses VS Code's root key", () => {
|
||||
const text = upsertServer(null, "servers", { type: "http", url: spec.url });
|
||||
expect(JSON.parse(text)).toEqual({ servers: { diffusion: { type: "http", url: spec.url } } });
|
||||
expect(readServer(text, "servers")).toEqual({ url: spec.url });
|
||||
// The same file read under the other root key has nothing of ours.
|
||||
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,
|
||||
mcpServers: { other: { command: "x", args: [] } },
|
||||
projects: { "/a": { allowedTools: [] } },
|
||||
});
|
||||
const after = JSON.parse(upsertServer(before, "mcpServers", { url: spec.url }));
|
||||
expect(after.numStartups).toBe(12);
|
||||
expect(after.projects).toEqual({ "/a": { allowedTools: [] } });
|
||||
expect(after.mcpServers.other).toEqual({ command: "x", args: [] });
|
||||
expect(after.mcpServers.diffusion).toEqual({ url: spec.url });
|
||||
});
|
||||
|
||||
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"] });
|
||||
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();
|
||||
});
|
||||
|
||||
it("reads the URL under each agent's key", () => {
|
||||
for (const key of ["url", "httpUrl", "serverUrl"]) {
|
||||
expect(readServer(upsertServer(null, "mcpServers", { [key]: spec.url }), "mcpServers")).toEqual({ url: spec.url });
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses to overwrite a file it cannot parse", () => {
|
||||
expect(() => upsertServer("{ not json", "mcpServers", { url: spec.url })).toThrow();
|
||||
expect(() => upsertServer("[1, 2]", "mcpServers", { url: spec.url })).toThrow();
|
||||
expect(readServer("{ not json", "mcpServers")).toBeNull();
|
||||
});
|
||||
|
||||
it("treats an empty file as no config", () => {
|
||||
expect(readServer("", "mcpServers")).toBeNull();
|
||||
expect(JSON.parse(upsertServer(" \n", "mcpServers", { url: spec.url }))).toEqual({ mcpServers: { diffusion: { url: spec.url } } });
|
||||
});
|
||||
|
||||
it("removes our entry and nothing else", () => {
|
||||
const before = JSON.stringify({
|
||||
numStartups: 12,
|
||||
mcpServers: { other: { command: "x", args: [] }, diffusion: { type: "http", url: spec.url } },
|
||||
});
|
||||
const after = removeServer(before, "mcpServers");
|
||||
expect(after).not.toBeNull();
|
||||
expect(JSON.parse(after as string)).toEqual({ numStartups: 12, mcpServers: { other: { command: "x", args: [] } } });
|
||||
expect(readServer(after, "mcpServers")).toBeNull();
|
||||
});
|
||||
|
||||
it("has nothing to remove from a config without our entry", () => {
|
||||
expect(removeServer(null, "mcpServers")).toBeNull();
|
||||
expect(removeServer("", "mcpServers")).toBeNull();
|
||||
expect(removeServer(JSON.stringify({ mcpServers: { other: { url: "u" } } }), "mcpServers")).toBeNull();
|
||||
expect(removeServer("{ not json", "mcpServers")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("toml configs (codex)", () => {
|
||||
it("appends a table to an existing config", () => {
|
||||
const before = 'model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n';
|
||||
const after = upsertServer(before, "toml", { url: spec.url });
|
||||
expect(after).toBe('model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n\n[mcp_servers.diffusion]\nurl = "http://127.0.0.1:3274/mcp"\n');
|
||||
expect(readServer(after, "toml")).toEqual({ url: spec.url });
|
||||
});
|
||||
|
||||
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"] });
|
||||
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 });
|
||||
});
|
||||
|
||||
it("starts a file from nothing", () => {
|
||||
const text = upsertServer(null, "toml", { url: spec.url });
|
||||
expect(text).toBe('[mcp_servers.diffusion]\nurl = "http://127.0.0.1:3274/mcp"\n');
|
||||
});
|
||||
|
||||
it("escapes quotes and backslashes in stdio paths", () => {
|
||||
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"] });
|
||||
});
|
||||
|
||||
it("reads nothing from a config without our table", () => {
|
||||
expect(readServer('model = "o3"\n', "toml")).toBeNull();
|
||||
expect(removeServer('model = "o3"\n', "toml")).toBeNull();
|
||||
});
|
||||
|
||||
it("removes our table from the end of a config", () => {
|
||||
const before = 'model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n';
|
||||
const connected = upsertServer(before, "toml", { url: spec.url });
|
||||
expect(removeServer(connected, "toml")).toBe(before);
|
||||
});
|
||||
|
||||
it("removes our table from between others without leaving a gap", () => {
|
||||
const before = 'model = "o3"\n\n[mcp_servers.diffusion]\nurl = "u"\n\n[mcp_servers.other]\ncommand = "x"\n';
|
||||
expect(removeServer(before, "toml")).toBe('model = "o3"\n\n[mcp_servers.other]\ncommand = "x"\n');
|
||||
});
|
||||
|
||||
it("empties a config that held only our table", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
277
apps/desktop/src/mcp-config.ts
Normal file
@ -0,0 +1,277 @@
|
||||
/* 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/. */
|
||||
|
||||
// How the app's MCP server is written into each agent's config, as pure
|
||||
// text transforms: no file system, no Electron, so the merge rules are
|
||||
// testable. `mcp-install.ts` decides which files and does the I/O.
|
||||
|
||||
/**
|
||||
* 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`.
|
||||
*/
|
||||
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).
|
||||
*/
|
||||
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>;
|
||||
|
||||
/** The stable id an agent is addressed by over IPC and in the UI. */
|
||||
export type AgentId =
|
||||
| "claude-code"
|
||||
| "claude-desktop"
|
||||
| "cursor"
|
||||
| "vscode"
|
||||
| "codex"
|
||||
| "antigravity"
|
||||
| "gemini-cli"
|
||||
| "windsurf"
|
||||
| "opencode";
|
||||
|
||||
/** 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 };
|
||||
|
||||
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;
|
||||
format: ConfigFormat;
|
||||
/** The entry for this agent: which transport it gets, under the keys its format uses. */
|
||||
entry(spec: McpServerSpec): ServerEntry;
|
||||
};
|
||||
|
||||
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 });
|
||||
|
||||
// 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
|
||||
// ~/.claude.json, the same file `claude mcp add --scope user` edits. VS Code
|
||||
// keeps its user-level servers under `servers` in the profile's mcp.json.
|
||||
// Antigravity shares one config across its IDE and CLI, and only accepts
|
||||
// `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-desktop",
|
||||
label: "Claude Desktop",
|
||||
marker: appData("Claude"),
|
||||
config: appData("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: "vscode",
|
||||
label: "VS Code (Copilot)",
|
||||
marker: appData("Code"),
|
||||
config: appData("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 }) },
|
||||
];
|
||||
|
||||
export function agentTarget(id: AgentId): AgentTarget {
|
||||
const target = AGENT_TARGETS.find((candidate) => candidate.id === id);
|
||||
if (!target) throw new Error(`Unknown agent: ${id}`);
|
||||
return target;
|
||||
}
|
||||
|
||||
/** Whether the agent runs our entry over stdio, and so needs the `dapi` binary. */
|
||||
export function needsBinary(target: AgentTarget): boolean {
|
||||
return "command" in target.entry({ url: "http://x", command: "x", args: [] });
|
||||
}
|
||||
|
||||
/**
|
||||
* The config with our entry set, leaving everything else as it was. `text`
|
||||
* is the file's current content, or null when there is none yet. Throws
|
||||
* when the file cannot be parsed: a config we cannot read is not one we
|
||||
* should overwrite.
|
||||
*/
|
||||
export function upsertServer(text: string | null, format: ConfigFormat, entry: ServerEntry): string {
|
||||
return format === "toml" ? upsertToml(text, entry) : upsertJson(text, format, entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* The config with our entry taken out, everything else untouched; null when
|
||||
* the file has no entry of ours (or cannot be parsed), so there is nothing
|
||||
* to write back. Other servers and unrelated keys stay as they were.
|
||||
*/
|
||||
export function removeServer(text: string | null, format: ConfigFormat): string | null {
|
||||
if (readServer(text, format) === null) return null;
|
||||
return format === "toml" ? removeToml(text as string) : removeJson(text as string, format);
|
||||
}
|
||||
|
||||
/** 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 function readServer(text: string | null, format: ConfigFormat): Registered | null {
|
||||
if (text === null) return null;
|
||||
const entry = format === "toml" ? readToml(text) : readJson(text, format);
|
||||
if (!entry) return null;
|
||||
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">;
|
||||
type JsonConfig = Record<string, unknown>;
|
||||
|
||||
function parseJson(text: string | null): JsonConfig {
|
||||
if (text === null || text.trim() === "") return {};
|
||||
const parsed: unknown = JSON.parse(text);
|
||||
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
||||
throw new Error("expected a JSON object at the top level");
|
||||
}
|
||||
return parsed as JsonConfig;
|
||||
}
|
||||
|
||||
function serverMap(config: JsonConfig, root: JsonFormat): Record<string, unknown> {
|
||||
const servers = config[root];
|
||||
return typeof servers === "object" && servers !== null && !Array.isArray(servers)
|
||||
? (servers as Record<string, unknown>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function upsertJson(text: string | null, root: JsonFormat, entry: ServerEntry): string {
|
||||
const config = parseJson(text);
|
||||
config[root] = { ...serverMap(config, root), [SERVER_NAME]: entry };
|
||||
return `${JSON.stringify(config, null, 2)}\n`;
|
||||
}
|
||||
|
||||
function removeJson(text: string, root: JsonFormat): string {
|
||||
const config = parseJson(text);
|
||||
const { [SERVER_NAME]: _ours, ...servers } = serverMap(config, root);
|
||||
config[root] = servers;
|
||||
return `${JSON.stringify(config, null, 2)}\n`;
|
||||
}
|
||||
|
||||
function readJson(text: string, root: JsonFormat): Record<string, unknown> | null {
|
||||
let config: JsonConfig;
|
||||
try {
|
||||
config = parseJson(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const entry = serverMap(config, root)[SERVER_NAME];
|
||||
return typeof entry === "object" && entry !== null ? (entry as Record<string, unknown>) : null;
|
||||
}
|
||||
|
||||
// --- TOML (Codex) ----------------------------------------------------------
|
||||
|
||||
// Our table, from its header up to the next table header or the end. A
|
||||
// header line is `[...]` at column 0; indented or commented ones are not.
|
||||
const TOML_TABLE = new RegExp(String.raw`^\[mcp_servers\.${SERVER_NAME}\][^\n]*\n(?:(?!\[)[^\n]*\n?)*`, "m");
|
||||
|
||||
function tomlString(value: string): string {
|
||||
return `"${value.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
|
||||
}
|
||||
|
||||
function tomlValue(value: string | string[] | boolean): string {
|
||||
if (typeof value === "boolean") return String(value);
|
||||
return Array.isArray(value) ? `[${value.map(tomlString).join(", ")}]` : tomlString(value);
|
||||
}
|
||||
|
||||
function tomlTable(entry: ServerEntry): string {
|
||||
const lines = Object.entries(entry).map(([key, value]) => `${key} = ${tomlValue(value)}`);
|
||||
return [`[mcp_servers.${SERVER_NAME}]`, ...lines, ""].join("\n");
|
||||
}
|
||||
|
||||
function upsertToml(text: string | null, entry: ServerEntry): string {
|
||||
const current = text ?? "";
|
||||
const table = tomlTable(entry);
|
||||
if (TOML_TABLE.test(current)) return current.replace(TOML_TABLE, table);
|
||||
const separator = current === "" || current.endsWith("\n\n") ? "" : current.endsWith("\n") ? "\n" : "\n\n";
|
||||
return `${current}${separator}${table}`;
|
||||
}
|
||||
|
||||
// Drops our table, then the blank lines it used to sit between so the file
|
||||
// does not end in (or contain) a growing gap after a connect/disconnect cycle.
|
||||
function removeToml(text: string): string {
|
||||
const rest = text.replace(TOML_TABLE, "").replace(/\n{3,}/g, "\n\n").trimEnd();
|
||||
return rest === "" ? "" : `${rest}\n`;
|
||||
}
|
||||
|
||||
function readToml(text: string): Record<string, unknown> | null {
|
||||
const table = text.match(TOML_TABLE)?.[0];
|
||||
if (!table) return null;
|
||||
const entry: Record<string, unknown> = {};
|
||||
for (const line of table.split("\n").slice(1)) {
|
||||
const scalar = line.match(/^(\w+)\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/);
|
||||
if (scalar) {
|
||||
entry[scalar[1]] = untomlString(scalar[2]);
|
||||
continue;
|
||||
}
|
||||
const list = line.match(/^(\w+)\s*=\s*\[([^\]]*)\]\s*$/);
|
||||
if (list) entry[list[1]] = [...list[2].matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => untomlString(m[1]));
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
function untomlString(value: string): string {
|
||||
return value.replaceAll('\\"', '"').replaceAll("\\\\", "\\");
|
||||
}
|
||||
182
apps/desktop/src/mcp-install.ts
Normal file
@ -0,0 +1,182 @@
|
||||
/* 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/. */
|
||||
|
||||
// Registers the app's MCP server with the agents on this machine, one agent
|
||||
// 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).
|
||||
|
||||
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 type { AgentPath, 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.
|
||||
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.
|
||||
*/
|
||||
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"] };
|
||||
}
|
||||
|
||||
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 readConfig(target: AgentTarget): string | null {
|
||||
const path = resolvePath(target.config);
|
||||
return existsSync(path) ? readFileSync(path, "utf8") : null;
|
||||
}
|
||||
|
||||
function writeConfig(target: AgentTarget, text: string): void {
|
||||
const path = resolvePath(target.config);
|
||||
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
|
||||
* 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 (app.isPackaged && current.command.includes("/AppTranslocation/")) {
|
||||
return "Move Diffusion Studio to the Applications folder and relaunch it first.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function agentStatus(target: AgentTarget, current: McpServerSpec): McpAgentStatus {
|
||||
const registered = readServer(readConfig(target), target.format);
|
||||
return {
|
||||
id: target.id,
|
||||
label: target.label,
|
||||
detected: existsSync(resolvePath(target.marker)),
|
||||
connected: registered !== null,
|
||||
config: resolvePath(target.config),
|
||||
unavailable: unavailableReason(target, current),
|
||||
};
|
||||
}
|
||||
|
||||
/** Every agent we know, with whether it is on this machine and whether its config carries our entry. */
|
||||
export function mcpStatus(): McpStatus {
|
||||
const current = spec();
|
||||
return { url: current.url, agents: AGENT_TARGETS.map((target) => agentStatus(target, current)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes our entry into the configs of `add` and takes it out of the configs
|
||||
* of `remove`, one file at a time, so one unreadable config does not stop
|
||||
* the rest. Other servers in the same file are left alone either way.
|
||||
*/
|
||||
export function applyMcp(request: McpApplyRequest): McpApplyResult {
|
||||
const current = spec();
|
||||
const result: McpApplyResult = { added: [], removed: [], failures: [] };
|
||||
|
||||
for (const id of request.add) {
|
||||
const target = agentTarget(id);
|
||||
const reason = unavailableReason(target, current);
|
||||
if (reason) {
|
||||
result.failures.push({ id, error: reason });
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
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}` });
|
||||
}
|
||||
}
|
||||
|
||||
for (const id of request.remove) {
|
||||
const target = agentTarget(id);
|
||||
try {
|
||||
const next = removeServer(readConfig(target), target.format);
|
||||
if (next !== null) writeConfig(target, next);
|
||||
result.removed.push(id);
|
||||
} catch (e) {
|
||||
result.failures.push({ id, error: `${target.config.path}: ${(e as Error).message}` });
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch-time self-heal for the stdio agents: an entry that still runs the
|
||||
* proxy from a bundle that moved (or was translocated when it was written)
|
||||
* is rewritten to the binary this build has. Entries the user wrote by hand
|
||||
* for something else are left alone.
|
||||
*/
|
||||
export function healMcpRegistrations(): void {
|
||||
if (!app.isPackaged) return;
|
||||
const current = spec();
|
||||
if (current.command === "" || current.command.includes("/AppTranslocation/")) return;
|
||||
|
||||
for (const target of AGENT_TARGETS) {
|
||||
const text = readConfig(target);
|
||||
const registered = readServer(text, target.format);
|
||||
if (!registered?.command) continue;
|
||||
if (!runsOurProxy(registered)) continue;
|
||||
const entry = target.entry(current);
|
||||
if (sameCommand(registered, entry)) continue;
|
||||
|
||||
try {
|
||||
writeConfig(target, upsertServer(text, target.format, entry));
|
||||
} catch {
|
||||
// best effort — the settings page remains as a manual fix
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -2,44 +2,21 @@
|
||||
* 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 { app, dialog, Menu } from "electron";
|
||||
import { app, Menu } from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
|
||||
import { CLI_LINK_PATH, installCli } from "./cli-install";
|
||||
|
||||
async function installCliFromMenu() {
|
||||
const result = await installCli();
|
||||
if (result.status === "cancelled") return;
|
||||
if (result.status === "installed") {
|
||||
await dialog.showMessageBox({
|
||||
type: "info",
|
||||
message: "The dapi command line tool was installed.",
|
||||
detail: `Linked at ${CLI_LINK_PATH}. Run "dapi --help" in a terminal to get started.`,
|
||||
});
|
||||
} else {
|
||||
await dialog.showMessageBox({
|
||||
type: "error",
|
||||
message: "Could not install the dapi command line tool.",
|
||||
detail: result.error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function setupAppMenu() {
|
||||
if (process.platform !== "darwin") return;
|
||||
// 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[] = []
|
||||
|
||||
const template: MenuItemConstructorOptions[] = [
|
||||
{
|
||||
if (process.platform === "darwin") {
|
||||
template.push({
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Install dapi Command Line Tool…",
|
||||
enabled: app.isPackaged,
|
||||
click: installCliFromMenu,
|
||||
},
|
||||
{ type: "separator" },
|
||||
{ role: "services" },
|
||||
{ type: "separator" },
|
||||
{ role: "hide" },
|
||||
@ -48,12 +25,15 @@ export function setupAppMenu() {
|
||||
{ type: "separator" },
|
||||
{ role: "quit" },
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
template.push(
|
||||
{ role: "fileMenu" },
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
];
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
}
|
||||
|
||||
@ -4,16 +4,17 @@
|
||||
|
||||
import { contextBridge, ipcRenderer, webUtils } from "electron";
|
||||
import { MAIN_WIRE } from "./main-channels";
|
||||
import { CLI_WIRE } from "@diffusionstudio/cli/channels";
|
||||
import { DAPI_WIRE } from "@diffusionstudio/dapi";
|
||||
|
||||
import type { IpcRendererEvent } from "electron";
|
||||
|
||||
const ALLOWED_RENDERER_TO_MAIN: ReadonlySet<string> = new Set([MAIN_WIRE.REQUEST]);
|
||||
const ALLOWED_RENDERER_TO_MAIN: ReadonlySet<string> = new Set([MAIN_WIRE.REQUEST, DAPI_WIRE.REPLY]);
|
||||
|
||||
const ALLOWED_MAIN_TO_RENDERER: ReadonlySet<string> = new Set([
|
||||
MAIN_WIRE.RESPONSE,
|
||||
MAIN_WIRE.EVENT,
|
||||
CLI_WIRE.CONNECT,
|
||||
DAPI_WIRE.CALL,
|
||||
DAPI_WIRE.CANCEL,
|
||||
]);
|
||||
|
||||
contextBridge.exposeInMainWorld("desktop", {
|
||||
|
||||
98
apps/desktop/src/projects.drafts.test.ts
Normal file
@ -0,0 +1,98 @@
|
||||
/* 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");
|
||||
});
|
||||
});
|
||||
86
apps/desktop/src/projects.init.test.ts
Normal file
@ -0,0 +1,86 @@
|
||||
/* 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/. */
|
||||
|
||||
// What `open` writes into a folder, and what it refuses: the promise the
|
||||
// tool reference makes is that a folder opened from anywhere on disk stays
|
||||
// the user's, gaining an entry and the record and nothing else.
|
||||
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } 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 { initProject } = await import("./projects");
|
||||
|
||||
let root: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), "init-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("initProject", () => {
|
||||
it("turns a missing folder into a project with an entry and a record, nothing else", async () => {
|
||||
const dir = join(root, "fresh");
|
||||
const project = await initProject(null, dir);
|
||||
expect(project.id).toMatch(/^[\w-]{21}$/);
|
||||
expect(project.name).toBe("fresh");
|
||||
expect(project.entry).toBe("index.tsx");
|
||||
expect((await readdir(dir)).sort()).toEqual(["index.tsx", "package.json"]);
|
||||
const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
|
||||
expect(pkg).toMatchObject({ projectId: project.id, displayName: "fresh", main: "index.tsx" });
|
||||
});
|
||||
|
||||
it("leaves a folder that is already a project untouched", async () => {
|
||||
const dir = join(root, "kept");
|
||||
await initProject(null, dir);
|
||||
const before = await readFile(join(dir, "package.json"), "utf8");
|
||||
await writeFile(join(dir, "notes.txt"), "mine");
|
||||
const again = await initProject(null, dir);
|
||||
expect(again.id).toBe(JSON.parse(before).projectId);
|
||||
expect(await readFile(join(dir, "package.json"), "utf8")).toBe(before);
|
||||
expect((await readdir(dir)).sort()).toEqual(["index.tsx", "notes.txt", "package.json"]);
|
||||
});
|
||||
|
||||
it("keeps what a package.json already says and only adds the record fields", async () => {
|
||||
const dir = join(root, "partial");
|
||||
await mkdir(dir);
|
||||
await writeFile(join(dir, "main.tsx"), "export default () => <stage />;\n");
|
||||
await writeFile(join(dir, "package.json"), JSON.stringify({ name: "partial", main: "main.tsx", scripts: { build: "x" } }, null, 2) + "\n");
|
||||
const project = await initProject(null, dir);
|
||||
const pkg = JSON.parse(await readFile(join(dir, "package.json"), "utf8"));
|
||||
expect(pkg.name).toBe("partial");
|
||||
expect(pkg.main).toBe("main.tsx");
|
||||
expect(pkg.scripts).toEqual({ build: "x" });
|
||||
expect(pkg.projectId).toBe(project.id);
|
||||
expect((await readdir(dir)).sort()).toEqual(["main.tsx", "package.json"]);
|
||||
});
|
||||
|
||||
it("leaves a JavaScript project entirely alone", async () => {
|
||||
const dir = join(root, "js");
|
||||
await mkdir(dir);
|
||||
await writeFile(join(dir, "index.jsx"), "export default () => null;\n");
|
||||
const project = await initProject(null, dir);
|
||||
expect(project.id).toBe("");
|
||||
expect(await readdir(dir)).toEqual(["index.jsx"]);
|
||||
});
|
||||
|
||||
it("refuses a relative path and a path that is a file", async () => {
|
||||
await expect(initProject(null, "relative/project")).rejects.toThrow(/absolute path/);
|
||||
const file = join(root, "a-file");
|
||||
await writeFile(file, "");
|
||||
await expect(initProject(null, file)).rejects.toThrow(/not a folder/);
|
||||
expect(await readFile(file, "utf8")).toBe("");
|
||||
});
|
||||
});
|
||||
51
apps/desktop/src/projects.locate.test.ts
Normal file
@ -0,0 +1,51 @@
|
||||
/* This Source Code Form is subject to the terms of the Mozilla Public
|
||||
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
|
||||
|
||||
// A project folder renamed or moved in Finder is found again next to where it
|
||||
// was, by the id in its record.
|
||||
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdir, mkdtemp, rename, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: { isPackaged: false, getPath: () => tmpdir() },
|
||||
dialog: {},
|
||||
shell: {},
|
||||
ipcMain: { on: () => { } },
|
||||
}));
|
||||
|
||||
const { findMovedProject, initProject } = await import("./projects");
|
||||
|
||||
let root: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), "locate-test-"));
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("findMovedProject", () => {
|
||||
it("finds a project renamed in place by its id", async () => {
|
||||
const project = await initProject(null, join(root, "golden-river"));
|
||||
await initProject(null, join(root, "another"));
|
||||
await rename(project.dir, join(root, "My Ad"));
|
||||
|
||||
const found = await findMovedProject(project.dir, project.id);
|
||||
expect(found).toMatchObject({ id: project.id, dir: join(root, "My Ad") });
|
||||
});
|
||||
|
||||
it("finds nothing when the folder left its parent, or the parent is gone", async () => {
|
||||
const project = await initProject(null, join(root, "golden-river"));
|
||||
await mkdir(join(root, "elsewhere", "deeper"), { recursive: true });
|
||||
await rename(project.dir, join(root, "elsewhere", "deeper", "My Ad"));
|
||||
|
||||
expect(await findMovedProject(project.dir, project.id)).toBeNull();
|
||||
expect(await findMovedProject(join(root, "gone", "golden-river"), project.id)).toBeNull();
|
||||
expect(await findMovedProject(project.dir, "")).toBeNull();
|
||||
});
|
||||
});
|
||||
217
apps/desktop/src/projects.watch.test.ts
Normal file
@ -0,0 +1,217 @@
|
||||
/* 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/. */
|
||||
|
||||
// What the watcher must and must not report. The app writes the files it
|
||||
// watches, so the whole question is whether a change is its own — answered by
|
||||
// content (see `noteContent`), which is what these pin down.
|
||||
|
||||
import { tmpdir } from "node:os";
|
||||
import { mkdir, mkdtemp, open, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { MAIN_CHANNELS, MAIN_WIRE } from "./main-channels";
|
||||
import { TEMP_PREFIX, tempPathFor, writeFileAtomic } from "./atomic";
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: { isPackaged: false, getPath: () => tmpdir() },
|
||||
dialog: {},
|
||||
shell: {},
|
||||
ipcMain: { on: () => { } },
|
||||
}));
|
||||
|
||||
const { noteContent, noteRenamed, readConfig, unwatchProject, watchProject, writeConfig, writeManifest } = await import("./projects");
|
||||
|
||||
let dir: string;
|
||||
let changed: string[] = [];
|
||||
|
||||
/** A window that only remembers which project files it was told about. */
|
||||
const window = {
|
||||
isDestroyed: () => false,
|
||||
webContents: {
|
||||
isLoading: () => false,
|
||||
send: (wire: string, envelope: { channel: string; data: { path: string } }) => {
|
||||
if (wire === MAIN_WIRE.EVENT && envelope.channel === MAIN_CHANNELS.PROJECTS_CHANGED) {
|
||||
changed.push(envelope.data.path);
|
||||
}
|
||||
},
|
||||
},
|
||||
} as unknown as Parameters<typeof watchProject>[0];
|
||||
|
||||
/** Long enough for an event to have arrived, for the cases where none may. */
|
||||
const settle = (ms = 400): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Waits for `path` to be reported, and fails the test when it never is. */
|
||||
async function waitFor(path: string, timeout = 4000): Promise<void> {
|
||||
const until = Date.now() + timeout;
|
||||
while (Date.now() < until) {
|
||||
if (changed.includes(path)) return;
|
||||
await settle(25);
|
||||
}
|
||||
expect(changed).toContain(path);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), "watch-test-"));
|
||||
changed = [];
|
||||
watchProject(window, dir);
|
||||
await settle(100);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
unwatchProject(dir);
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("watchProject", () => {
|
||||
it("reports a file someone else writes", async () => {
|
||||
await writeFile(join(dir, "index.tsx"), "export const stage = 1;\n", "utf8");
|
||||
await waitFor("index.tsx");
|
||||
});
|
||||
|
||||
// Without this the claim above proves nothing: a rename that never reached
|
||||
// the watcher would look exactly like a claim that worked.
|
||||
it("reports a file someone else replaces by rename", async () => {
|
||||
await writeFileAtomic(join(dir, "index.tsx"), "export const stage = 1;\n");
|
||||
await waitFor("index.tsx");
|
||||
});
|
||||
|
||||
it("says nothing about a write the app claimed", async () => {
|
||||
const file = join(dir, "index.tsx");
|
||||
const text = "export const stage = 1;\n";
|
||||
noteContent(file, text);
|
||||
await writeFileAtomic(file, text);
|
||||
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports an outside edit that lands right after one of the app's own", async () => {
|
||||
const file = join(dir, "index.tsx");
|
||||
noteContent(file, "ours\n");
|
||||
await writeFileAtomic(file, "ours\n");
|
||||
// No claim: this one is someone else's, however close behind it comes.
|
||||
await writeFile(file, "theirs\n", "utf8");
|
||||
|
||||
await waitFor("index.tsx");
|
||||
});
|
||||
|
||||
it("says nothing about a write that changes nothing", async () => {
|
||||
const file = join(dir, "notes.txt");
|
||||
await writeFile(file, "same\n", "utf8");
|
||||
await waitFor("notes.txt");
|
||||
|
||||
changed = [];
|
||||
await writeFile(file, "same\n", "utf8");
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports a file someone else deletes", async () => {
|
||||
const file = join(dir, "notes.txt");
|
||||
await writeFile(file, "here\n", "utf8");
|
||||
await waitFor("notes.txt");
|
||||
|
||||
changed = [];
|
||||
await rm(file);
|
||||
await waitFor("notes.txt");
|
||||
});
|
||||
|
||||
it("ignores the temp files an atomic write leaves in the folder", async () => {
|
||||
await writeFile(join(dir, `${TEMP_PREFIX}index.tsx.1-1`), "half a file", "utf8");
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
});
|
||||
|
||||
it("says nothing about an asset streamed to a temp file and renamed into place", async () => {
|
||||
await mkdir(join(dir, "assets"), { recursive: true });
|
||||
await waitFor("assets");
|
||||
const file = join(dir, "assets", "clip.bin");
|
||||
|
||||
changed = [];
|
||||
const temp = tempPathFor(file);
|
||||
const handle = await open(temp, "wx");
|
||||
// Positioned chunks, the way an encoder writes one.
|
||||
await handle.write(Buffer.from("chunk one"), 0, 9, 0);
|
||||
await settle();
|
||||
await handle.write(Buffer.from(" and two"), 0, 8, 9);
|
||||
await handle.close();
|
||||
await settle();
|
||||
// Nothing has appeared where the library looks, so there is nothing to say.
|
||||
expect(changed).toEqual([]);
|
||||
|
||||
await noteRenamed(temp, file);
|
||||
await rename(temp, file);
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
});
|
||||
|
||||
it("reports an asset someone else renames into place", async () => {
|
||||
await mkdir(join(dir, "assets"), { recursive: true });
|
||||
await waitFor("assets");
|
||||
|
||||
changed = [];
|
||||
const temp = tempPathFor(join(dir, "assets", "clip.bin"));
|
||||
await writeFile(temp, "theirs", "utf8");
|
||||
await rename(temp, join(dir, "assets", "clip.bin"));
|
||||
|
||||
await waitFor("assets/clip.bin");
|
||||
});
|
||||
|
||||
// The claim for a file too big to hash is its size and mtime, which a rename
|
||||
// has to carry across untouched for `noteRenamed` to mean anything.
|
||||
it("says nothing about a file too big to hash, claimed before its rename", async () => {
|
||||
const file = join(dir, "assets", "big.bin");
|
||||
await mkdir(join(dir, "assets"), { recursive: true });
|
||||
await waitFor("assets");
|
||||
|
||||
changed = [];
|
||||
const temp = tempPathFor(file);
|
||||
await writeFile(temp, Buffer.alloc(9 * 1024 * 1024, 7));
|
||||
await noteRenamed(temp, file);
|
||||
await rename(temp, file);
|
||||
|
||||
await settle();
|
||||
expect(changed).toEqual([]);
|
||||
});
|
||||
|
||||
it("says nothing about the manifest it writes itself", async () => {
|
||||
await writeManifest(dir, { assets: [{ source: "assets/clip.mp4" }] });
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
@ -1,191 +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 { app } from "electron";
|
||||
import { existsSync, lstatSync, mkdirSync, readdirSync, readlinkSync, rmSync, symlinkSync } from "node:fs";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import type { SkillsInstallResult } from "./main-channels";
|
||||
|
||||
const AGENT_SKILLS_DIRS = [
|
||||
".adal/skills",
|
||||
".agents/skills",
|
||||
".aider-desk/skills",
|
||||
".astrbot/data/skills",
|
||||
".augment/skills",
|
||||
".autohand/skills",
|
||||
".bob/skills",
|
||||
".claude/skills",
|
||||
".clawdbot/skills",
|
||||
".codeartsdoer/skills",
|
||||
".codebuddy/skills",
|
||||
".codeium/windsurf/skills",
|
||||
".codemaker/skills",
|
||||
".codestudio/skills",
|
||||
".codex/skills",
|
||||
".commandcode/skills",
|
||||
".config/agents/skills",
|
||||
".config/crush/skills",
|
||||
".config/devin/skills",
|
||||
".config/goose/skills",
|
||||
".config/kimchi/harness/skills",
|
||||
".config/opencode/skills",
|
||||
".continue/skills",
|
||||
".copilot/skills",
|
||||
".cursor/skills",
|
||||
".deepagents/agent/skills",
|
||||
".factory/skills",
|
||||
".firebender/skills",
|
||||
".forge/skills",
|
||||
".gemini/antigravity-cli/skills",
|
||||
".gemini/antigravity/skills",
|
||||
".gemini/skills",
|
||||
".grok/skills",
|
||||
".hermes/skills",
|
||||
".iflow/skills",
|
||||
".inferencesh/skills",
|
||||
".jazz/skills",
|
||||
".junie/skills",
|
||||
".kilocode/skills",
|
||||
".kiro/skills",
|
||||
".kode/skills",
|
||||
".lingma/skills",
|
||||
".mcpjam/skills",
|
||||
".minimax/skills",
|
||||
".moltbot/skills",
|
||||
".moxby/skills",
|
||||
".mux/skills",
|
||||
".neovate/skills",
|
||||
".ona/skills",
|
||||
".openclaw/skills",
|
||||
".openhands/skills",
|
||||
".pi/agent/skills",
|
||||
".pochi/skills",
|
||||
".posit/assistant/skills",
|
||||
".qoder-cn/skills",
|
||||
".qoder/skills",
|
||||
".qwen/skills",
|
||||
".reasonix/skills",
|
||||
".roo/skills",
|
||||
".rovodev/skills",
|
||||
".snowflake/cortex/skills",
|
||||
".tabnine/agent/skills",
|
||||
".terramind/skills",
|
||||
".tinycloud/skills",
|
||||
".trae-cn/skills",
|
||||
".trae/skills",
|
||||
".vibe/skills",
|
||||
".zcode/skills",
|
||||
".zencoder/skills",
|
||||
];
|
||||
|
||||
const FALLBACK_AGENT_DIR = ".claude/skills";
|
||||
|
||||
function stagedSkillsDir(): string {
|
||||
return app.isPackaged
|
||||
? join(process.resourcesPath, "skills")
|
||||
: join(app.getAppPath(), "skills");
|
||||
}
|
||||
|
||||
function stagedSkillNames(): string[] {
|
||||
const dir = stagedSkillsDir();
|
||||
if (!existsSync(dir)) return [];
|
||||
return readdirSync(dir, { withFileTypes: true })
|
||||
.filter((entry) => entry.isDirectory())
|
||||
.map((entry) => entry.name);
|
||||
}
|
||||
|
||||
// Agents whose config dir exists on this machine, falling back to Claude Code
|
||||
// so a machine with no agent yet still gets set up for the primary one.
|
||||
function targetAgentDirs(): string[] {
|
||||
const home = homedir();
|
||||
const present = AGENT_SKILLS_DIRS.filter((dir) => existsSync(join(home, dirname(dir))));
|
||||
return (present.length > 0 ? present : [FALLBACK_AGENT_DIR]).map((dir) => join(home, dir));
|
||||
}
|
||||
|
||||
// `existsSync` follows symlinks, so a dangling link doesn't count.
|
||||
export function isSkillsInstalled(): boolean {
|
||||
const home = homedir();
|
||||
const marker = stagedSkillNames()[0] ?? "editor";
|
||||
return AGENT_SKILLS_DIRS.some((dir) => existsSync(join(home, dir, marker, "SKILL.md")));
|
||||
}
|
||||
|
||||
// ln -sf semantics that never clobber real files: an existing symlink is
|
||||
// repointed (ours or the skills CLI's — the user asked to install), but a
|
||||
// real directory (a `skills add --copy` install) is left alone.
|
||||
function linkSkill(linkPath: string, target: string): void {
|
||||
try {
|
||||
if (!lstatSync(linkPath).isSymbolicLink()) return;
|
||||
rmSync(linkPath);
|
||||
} catch {
|
||||
// nothing at linkPath
|
||||
}
|
||||
symlinkSync(target, linkPath);
|
||||
}
|
||||
|
||||
export function installSkills(): SkillsInstallResult {
|
||||
const source = stagedSkillsDir();
|
||||
// A quarantined first launch runs from a translocated read-only mount whose
|
||||
// path won't survive the next launch — linking to it would dangle.
|
||||
if (source.includes("/AppTranslocation/")) {
|
||||
return {
|
||||
status: "error",
|
||||
error: "Move Diffusion Studio to the Applications folder and relaunch it, then try again.",
|
||||
};
|
||||
}
|
||||
const skills = stagedSkillNames();
|
||||
if (skills.length === 0) {
|
||||
return {
|
||||
status: "error",
|
||||
error: app.isPackaged
|
||||
? "The app bundle is missing its skills resources."
|
||||
: "Skills are not staged — run `npm run stage:skills` in apps/desktop.",
|
||||
};
|
||||
}
|
||||
try {
|
||||
for (const agentDir of targetAgentDirs()) {
|
||||
mkdirSync(agentDir, { recursive: true });
|
||||
for (const name of skills) {
|
||||
linkSkill(join(agentDir, name), join(source, name));
|
||||
}
|
||||
}
|
||||
return { status: "installed" };
|
||||
} catch (e) {
|
||||
return { status: "error", error: (e as Error).message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Launch-time self-heal: links created by installSkills break when the app
|
||||
* moves or was translocated when they were made. Any symlink that targets a
|
||||
* Diffusion Studio bundle but not the running app's resources is repointed.
|
||||
* Links owned by the skills CLI and copied installs are left alone.
|
||||
*/
|
||||
export function healSkillsLinks(): void {
|
||||
if (!app.isPackaged) return;
|
||||
const source = stagedSkillsDir();
|
||||
if (source.includes("/AppTranslocation/")) return;
|
||||
|
||||
const home = homedir();
|
||||
for (const dir of AGENT_SKILLS_DIRS) {
|
||||
for (const name of stagedSkillNames()) {
|
||||
const linkPath = join(home, dir, name);
|
||||
let target: string;
|
||||
try {
|
||||
target = readlinkSync(linkPath);
|
||||
} catch {
|
||||
continue; // missing, or not a symlink
|
||||
}
|
||||
const ours = target.includes("Diffusion Studio") || target.includes("/AppTranslocation/");
|
||||
const current = join(source, name);
|
||||
if (!ours || target === current) continue;
|
||||
try {
|
||||
rmSync(linkPath);
|
||||
symlinkSync(current, linkPath);
|
||||
} catch {
|
||||
// best effort — the install button remains as a manual fix
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||