Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 10 additions & 5 deletions .github/workflows/desktop-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -67,15 +67,20 @@ jobs:
codesign --verify --deep --strict "$app"
- name: Build and smoke-test DMG
run: |
staging="$RUNNER_TEMP/desktop-dmg"
mount="$RUNNER_TEMP/desktop-mount"
mkdir -p "$staging" "$mount" release-assets
ditto apps/desktop/build/mac-arm64/OpenDirector.app "$staging/OpenDirector.app"
ln -s /Applications "$staging/Applications"
installer="$PWD/apps/desktop/installer/macos"
mkdir -p "$mount" release-assets
dmg="OpenDirector-v${DESKTOP_VERSION}-mac-arm64-adhoc.dmg"
hdiutil create -volname OpenDirector -srcfolder "$staging" -format UDZO "release-assets/$dmg"
uv tool run --from 'dmgbuild==2.0.0' dmgbuild \
-s "$installer/dmg-settings.py" \
-D "app=$PWD/apps/desktop/build/mac-arm64/OpenDirector.app" \
-D "background=$installer/background.png" \
OpenDirector "release-assets/$dmg"
hdiutil attach "release-assets/$dmg" -readonly -nobrowse -mountpoint "$mount"
trap 'hdiutil detach "$mount"' EXIT
test -s "$mount/.DS_Store"
test -s "$mount/.background.tiff"
test "$(readlink "$mount/Applications")" = /Applications
installed=$(mktemp -d "$RUNNER_TEMP/desktop-install.XXXXXX")/OpenDirector.app
ditto "$mount/OpenDirector.app" "$installed"
codesign --verify --deep --strict "$installed"
Expand Down
5 changes: 3 additions & 2 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,12 +105,13 @@ def open_project(project_id: UUID, x_opendirector_session: UUID = Header()):

@router.post('/projects/{project_id}/open-canvas')
def open_project_canvas(project_id: UUID, x_opendirector_session: UUID = Header()):
# The canvas needs its reference edges on first render too. Reuse the
# The canvas needs its reference edges and text on first render too. Reuse the
# single snapshot this open read already published instead of making the
# page read the same project again through GET /canvas. The no-flag
# route above still returns a bare ProjectSnapshot.
snapshot = projects.open(project_id, str(x_opendirector_session))
return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot)}
return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot),
'texts': canvas.text_contents(snapshot)}

@router.put('/sessions/{session_id}')
def heartbeat(session_id: UUID, value: Session):
Expand Down
Binary file added apps/desktop/installer/macos/background.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added apps/desktop/installer/macos/background@2x.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
20 changes: 20 additions & 0 deletions apps/desktop/installer/macos/dmg-settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from pathlib import Path

app = Path(defines["app"])
format = "UDZO"
filesystem = "APFS"
files = [str(app)]
symlinks = {"Applications": "/Applications"}

# Keep presentation on the volume. Hiding the app extension adds Finder
# metadata to the signed bundle, which fails strict signature validation.
background = defines["background"]
window_rect = ((150, 150), (700, 410))
icon_locations = {app.name: (190, 147), "Applications": (510, 147)}
icon_size = 90
text_size = 13
show_toolbar = False
show_tab_view = False
show_sidebar = False
show_pathbar = False
show_status_bar = False
60 changes: 46 additions & 14 deletions apps/desktop/scripts/smoke-window.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,35 +14,35 @@ export async function smokeWindow({ window, host, getLocale }) {
})()`);
if (result.health.status !== 'ok' || result.projects !== 200 || !result.isolated || !result.bridge) throw new Error('Desktop smoke failed');
await waitFor(() => window.webContents.executeJavaScript('document.querySelectorAll("button").length > 2'), 'Workbench did not become interactive');
if (process.platform === 'win32' && await window.webContents.executeJavaScript('!localStorage.getItem("opendirector.modelSetup.v1")')) {
await checkWindowsWelcomeCaption(window);
if (process.env.OPENDIRECTOR_DESKTOP_DATA && !process.env.OPENDIRECTOR_DESKTOP_SMOKE_MEDIA_PROJECT) {
if (process.platform === 'win32') await checkWindowsWelcomeCaption(window);
await completeWelcome(window);
}
await window.webContents.executeJavaScript('document.querySelector(".cw-welcome-secondary")?.click()');
await waitFor(() => window.webContents.executeJavaScript('!!document.querySelector(".react-flow") && !!document.querySelector(".cw-save-status i.saved")'), 'Canvas did not open');
result.projectIds = await waitFor(() => window.webContents.executeJavaScript(`fetch('/api/creation/projects', {headers: {'X-OpenDirector-Request': '1'}})
.then(r => r.json()).then(value => value.projects.length ? value.projects.map(project => project.id).sort() : null)`), 'Canvas project was not persisted');
await delay(500);
await window.webContents.executeJavaScript('document.querySelector(".cw-welcome-secondary")?.click()');
await delay(300);
if (await window.webContents.executeJavaScript('!!document.querySelector("dialog[open]")')) throw new Error('A dialog obscures the canvas');
if (process.platform === 'win32') await checkWindowsCaption(window);
if (process.env.OPENDIRECTOR_DESKTOP_DATA) {
const projectId = result.projectIds.length === 1
? result.projectIds[0]
: process.env.OPENDIRECTOR_DESKTOP_SMOKE_MEDIA_PROJECT;
if (result.projectIds.length === 1) await dropMedia(window);
const fingerprints = Object.fromEntries(
Object.entries({ image: 'png', video: 'mp4', audio: 'wav' }).map(([kind, extension]) => {
const bytes = readFileSync(join(process.env.OPENDIRECTOR_DESKTOP_DATA, `desktop-drop.${extension}`));
return [kind, 'sha256:' + createHash('sha256').update(bytes).digest('hex')];
}),
);
const fingerprints = [
['image', 'desktop-drop.png'],
['video', 'desktop-drop.mp4'],
['audio', 'desktop-drop.wav'],
['audio', 'desktop-welcome.wav'],
].map(([kind, name]) => {
const bytes = readFileSync(join(process.env.OPENDIRECTOR_DESKTOP_DATA, name));
return [kind, 'sha256:' + createHash('sha256').update(bytes).digest('hex')];
});
let state;
try {
await waitFor(async () => {
state = await droppedMediaState(window, projectId, fingerprints);
return state.saved;
}, 'Dropped video, image and audio were not saved');
}, 'Welcome import and dropped media were not saved');
} catch (error) {
throw new Error(`${error.message}: ${JSON.stringify(state)}`, { cause: error });
}
Expand Down Expand Up @@ -287,6 +287,38 @@ async function smokeLargeVideo(window, host, projectId, fixture, firstLaunch) {
return binding;
}

async function completeWelcome(window) {
const { webContents } = window;
for (const [selector, label, error] of [
['.cw-welcome-intro .cw-welcome-primary', null, 'Welcome did not offer Get started'],
['.cw-welcome-connection-options > button:last-child', null, 'Welcome did not offer an existing harness'],
['.cw-welcome-options > button', 'OpenCode', 'Bundled OpenCode was not available in Welcome'],
]) {
await waitFor(() => webContents.executeJavaScript(`(() => {
const label = ${JSON.stringify(label)};
const buttons = document.querySelectorAll(${JSON.stringify(`dialog.cw-welcome[open] ${selector}`)});
const button = [...buttons].find(item => !item.disabled && (!label || item.querySelector('strong')?.textContent === label));
if (!button) return false;
button.click();
return true;
})()`), error);
}
const input = 'dialog.cw-welcome[open] input[type="file"]';
await waitFor(() => webContents.executeJavaScript(`!!document.querySelector(${JSON.stringify(input)})`), 'Welcome did not reach the task chooser');
const debuggerSession = webContents.debugger;
debuggerSession.attach();
try {
const { root } = await debuggerSession.sendCommand('DOM.getDocument');
const { nodeId } = await debuggerSession.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: input });
await debuggerSession.sendCommand('DOM.setFileInputFiles', {
nodeId, files: [join(process.env.OPENDIRECTOR_DESKTOP_DATA, 'desktop-welcome.wav')],
});
} finally {
debuggerSession.detach();
}
await waitFor(() => webContents.executeJavaScript('!document.querySelector("dialog.cw-welcome[open]")'), 'Welcome did not complete after importing media');
}

async function dropMedia(window) {
const { webContents } = window;
const { x, y } = await webContents.executeJavaScript(`(() => {
Expand Down Expand Up @@ -314,7 +346,7 @@ async function droppedMediaState(window, projectId, fingerprints) {
});
if (!response.ok) return { status: response.status };
const { canvasItems, assets } = await response.json();
const saved = Object.entries(${JSON.stringify(fingerprints)}).every(([kind, fingerprint]) =>
const saved = ${JSON.stringify(fingerprints)}.every(([kind, fingerprint]) =>
canvasItems.some(item => item.kind === kind && item.binding.role === 'material' &&
assets.some(asset => asset.id === item.binding.objectRef.assetId && asset.kind === kind &&
asset.provenance.source === 'upload' && asset.fingerprint === fingerprint)));
Expand Down
18 changes: 14 additions & 4 deletions apps/desktop/scripts/smoke.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { copyFile, mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { access, copyFile, mkdtemp, readFile, realpath, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { delimiter, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { createLargeVideo } from './large-video.mjs';
import { spawn } from 'node:child_process';
import { execFileSync, spawn } from 'node:child_process';

const binary = process.argv[2];
if (!binary) throw new Error('Usage: node scripts/smoke.mjs /path/to/packaged/OpenDirector');
Expand All @@ -14,13 +14,20 @@ let mediaProject;
let sidebarOpen = false;
let largeVideo;
try {
const runtime = resolve(dirname(binary), process.platform === 'darwin' ? '../Resources/runtime' : 'resources/runtime');
const { python } = JSON.parse(await readFile(join(runtime, 'manifest.json'), 'utf8'));
// Give the isolated smoke process a real installed harness for the welcome flow.
const harnessBin = execFileSync(join(runtime, python), ['-I', '-B', '-X', 'utf8', '-c',
'from opendirector.installation import BUNDLED; print(BUNDLED / "bin")'], { encoding: 'utf8' }).trim();
await access(join(harnessBin, process.platform === 'win32' ? 'opencode.exe' : 'opencode'));
const video = process.platform === 'win32'
? await createLargeVideo(join(directory, 'large-video.mp4'))
: null;
const fixtures = [
['desktop-drop.mp4', '../../../tests/fixtures/timeline-text/visual-a.mp4'],
['desktop-drop.wav', '../../../tests/fixtures/timeline-text/audio-a.wav'],
['desktop-drop.png', '../../../src/assets/open_director_logo.png'],
['desktop-welcome.wav', '../../../tests/fixtures/timeline-text/audio-b.wav'],
];
for (const [name, source] of fixtures) {
await copyFile(fileURLToPath(new URL(source, import.meta.url)), join(directory, name));
Expand All @@ -29,6 +36,9 @@ try {
const child = spawn(binary, ['--smoke'], {
env: {
...process.env,
PATH: [harnessBin, process.env.PATH].filter(Boolean).join(delimiter),
OPENCODE_DISABLE_MODELS_FETCH: '1',
OPENCODE_PURE: '1',
OPENDIRECTOR_DESKTOP_DATA: directory,
OPENDIRECTOR_DESKTOP_SMOKE_LARGE_VIDEO: video ? JSON.stringify(video) : '',
OPENDIRECTOR_DESKTOP_SMOKE_MEDIA_PROJECT: mediaProject ?? '',
Expand Down Expand Up @@ -60,5 +70,5 @@ try {
if (previous && JSON.stringify(previous) !== JSON.stringify(current)) throw new Error('Reopening changed the project identities');
previous = current;
}
process.stdout.write('Packaged canvas, media drag-and-drop, authenticated API, isolation, both locales, hidden-window Host, reopen and sidebar preferences: passed\n');
process.stdout.write('Packaged first run, canvas, media drag-and-drop, authenticated API, isolation, both locales, hidden-window Host, reopen and sidebar preferences: passed\n');
} finally { await rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); }
1 change: 1 addition & 0 deletions docs/development/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,7 @@ node tests/browser/reference_reconnect.mjs # 参考连线删除后重连
node tests/browser/context_menu_dismissal.mjs # 右键菜单关闭
node tests/browser/mp4_export.mjs # 合成 MP4(WebCodecs + 软件 AAC)
node tests/browser/new_image_node_outputs.mjs # 新建图片节点采用所选适配器的比例与尺寸
node tests/browser/canvas_progressive_load.mjs # 画布结构先可用,节点媒体独立加载、失败重试且不改写内容
```

历史版本预览回归([#393](https://github.com/ThinkFlowLab/OpenDirector/issues/393))沿用上述隔离服务:运行 `node tests/browser/node_versions.mjs`;设置 `HISTORY_PREVIEW_PROBE=delay` 会延迟目标缩略图一秒,完整旅程应通过。设置 `HISTORY_PREVIEW_PROBE=missing` 会注入缩略图 404,预期脚本失败并输出 `History preview unavailable`、目标资产 ID、HTTP 状态和媒体提示;它是故障诊断检查,不是成功旅程。清除变量后恢复正常运行。布局断言必须等待预期资产的图片加载成功,不能以提示词出现代替预览就绪。
Expand Down
20 changes: 20 additions & 0 deletions docs/guides/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,26 @@

[English](installation.md) · [简体中文](installation.zh-CN.md) · [Back to README](../../README.md)

<a name="macos-first-launch"></a>

## First launch on macOS

The desktop DMG is for Apple silicon Macs. Download it from [OpenDirector's official GitHub Releases](https://github.com/ThinkFlowLab/OpenDirector/releases).

1. Open the DMG in Finder. Drag **OpenDirector** into **Applications**.
2. In Finder, open **Applications** and double-click **OpenDirector**.
3. This build is not notarized by Apple. If macOS says it can't verify OpenDirector or its developer, confirm that the DMG came from the official release. Dismiss the alert, then go to **System Settings → Privacy & Security**, scroll to **Security**, and click **Open Anyway** for OpenDirector. Follow the confirmation prompt. [Apple's first-launch instructions](https://support.apple.com/en-us/102445)

If **Open Anyway** is missing, try opening OpenDirector from **Applications** once and return to **Privacy & Security**. If your organization manages the Mac, contact your administrator.

If Finder can't open the DMG, download it again and compare its SHA-256 with the `.sha256` file next to that exact installer on GitHub Releases. Run `shasum -a 256` followed by the path to the downloaded DMG to print its checksum. If the DMG still won't open, report the exact message and the macOS version.

If macOS says the **app** is damaged, reports malware, or says the app will damage your computer, stop and report the alert.

<a name="source-installation"></a>

## Install from source or a wheel

### 1. Prepare your environment

| Dependency | Requirement |
Expand Down
20 changes: 20 additions & 0 deletions docs/guides/installation.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,26 @@

[English](installation.md) · [简体中文](installation.zh-CN.md) · [返回首页](../../README.zh-CN.md)

<a name="macos-first-launch"></a>

## macOS 首次打开

桌面版 DMG 适用于搭载 Apple 芯片的 Mac。请从 [OpenDirector 官方 GitHub Releases](https://github.com/ThinkFlowLab/OpenDirector/releases) 下载安装包。

1. 在访达中打开 DMG,把 **OpenDirector** 拖入「应用程序」。
2. 在访达的「应用程序」中双击 **OpenDirector**。
3. 此版本未经 Apple 公证。若 macOS 提示无法验证 OpenDirector 或其开发者,先确认 DMG 来自官方 Release。关闭提示后,打开「系统设置 → 隐私与安全性」(部分版本称「隐私与安全」),向下滚动到「安全性」,找到 OpenDirector,点按「仍要打开」并按提示确认。[Apple 的首次打开说明](https://support.apple.com/zh-cn/102445)

如果看不到「仍要打开」,请先从「应用程序」尝试打开 OpenDirector 一次,再回到「隐私与安全性」。如果 Mac 由单位管理,请联系管理员。

如果访达无法打开 DMG,请重新下载,并用 GitHub Releases 上对应安装包旁的 `.sha256` 文件核对校验值。在终端输入 `shasum -a 256` 和下载的 DMG 路径,即可查看校验值。如果 DMG 仍打不开,请反馈原始提示和 macOS 版本。

如果 macOS 提示 **App** 已损坏、识别到恶意软件,或提示 App 会损坏电脑,请停止并反馈原始提示。

<a name="source-installation"></a>

## 通过源码或 wheel 安装

### 1. 准备环境

| 依赖 | 要求 |
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/opendirector/application/creation_assets.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,10 @@ def open_media(self, project_id, asset_id, *, snapshot=None):
with self.projects.local.transaction() as db:
self.projects._recover()
if snapshot is None:
path, _, records = self.projects._load(db, project_id)
snapshot = records[0].snapshot
# A head whose chain was already proven needs no replay per read.
path, manifest = self.projects._find(db, project_id)
record, validated = self.projects._current_record(db, project_id, path, manifest)
snapshot = (record if validated else self.projects._load(db, project_id)[2][0]).snapshot
else:
if snapshot.project.id != UUID(str(project_id)):
raise ProjectError('素材读取快照不属于当前工程。', 409)
Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/opendirector/application/creation_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -826,6 +826,24 @@ def check_asset(asset):

return check_asset

def text_contents(self, snapshot):
"""Text shown by canvas items, read with the snapshot that opens the canvas.

An unreadable body is left out so only that item reports it.
"""
contents = {}
for item in snapshot.canvasItems:
asset = current_asset(snapshot, item)
if asset is None or asset.kind != 'text' or str(asset.id) in contents:
continue
try:
stream, _ = self.assets.open_media(asset.projectId, asset.id, snapshot=snapshot)
with stream:
contents[str(asset.id)] = stream.read().decode('utf-8-sig', 'replace')
except (ContractError, ProjectError, OSError):
continue
return contents

def reference_edges(self, project_id, snapshot=None, check_asset=None):
"""Authoritative canvas reference states for one snapshot.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def reference_catalog(self, project_id):
for asset in snapshot.assets:
file_available = True
try:
service.reference_available(project_id, asset.id)
service.reference_available(project_id, asset.id, snapshot=snapshot)
except (ContractError, ProjectError, OSError, ValueError):
file_available = False
available = file_available and (asset.id in listed or asset.id in owners)
Expand Down
4 changes: 4 additions & 0 deletions scripts/run-browser-suite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ const workflows = [
name: "canvas switch",
script: "tests/browser/canvas_switch.mjs",
},
{
name: "canvas progressive load",
script: "tests/browser/canvas_progressive_load.mjs",
},
{
name: "structured editors",
script: "tests/browser/structured_editors.mjs",
Expand Down
17 changes: 17 additions & 0 deletions src/backend/assetSource.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/** A stable reference to a saved asset in a node's media fields.
*
* Object URLs depend on what this page has loaded, so they cannot describe
* project content. This value stays the same before and after the bytes arrive
* and is resolved only where media is displayed or read. */
const PREFIX = "opendirector-asset://";

export const assetSource = (projectId: string, assetId: string) =>
`${PREFIX}${projectId}/${assetId}`;

export function parseAssetSource(src: string | null | undefined) {
if (!src?.startsWith(PREFIX)) return undefined;
const [projectId, assetId, extra] = src.slice(PREFIX.length).split("/");
return projectId && assetId && extra === undefined
? { projectId, assetId }
: undefined;
}
Loading