snapshot of https://github.com/toeverything/AFFiNE.git (canary, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Build & Test / Analyze (javascript, affine) (push) Failing after 4s
Build & Test / Analyze (typescript, affine) (push) Failing after 3s
Build & Test / Rust test filter (push) Failing after 4s
Build & Test / Check yarn binary (push) Failing after 3s
Build & Test / E2E BlockSuite Test (3) (push) Failing after 3s
Build & Test / Analyze (javascript, blocksuite) (push) Failing after 3s
Build & Test / Analyze (typescript, blocksuite) (push) Failing after 3s
Build & Test / Mobile native build filter (push) Failing after 3s
Build & Test / E2E BlockSuite Test (1) (push) Failing after 4s
Build & Test / E2E BlockSuite Test (2) (push) Failing after 4s
Build & Test / E2E Mobile Test (1) (push) Failing after 3s
Build & Test / Unit Test (1) (push) Has been skipped
Build & Test / Unit Test (2) (push) Has been skipped
Build & Test / Unit Test (3) (push) Has been skipped
Build & Test / Unit Test (4) (push) Has been skipped
Build & Test / Unit Test (5) (push) Has been skipped
Build & Test / Native Unit Test (push) Has been skipped
Build & Test / E2E BlockSuite Test (4) (push) Failing after 3s
Build & Test / E2E BlockSuite Test (5) (push) Failing after 3s
Build & Test / E2E BlockSuite Cross Browser Test (push) Failing after 3s
Build & Test / E2E Mobile Test (2) (push) Failing after 3s
Build & Test / Build AFFiNE native (x86_64-unknown-linux-gnu) (push) Failing after 3s
Build & Test / Build Server native (push) Failing after 3s
Build & Test / Check Git Status (push) Has been skipped
Build & Test / Server Test (0, 4) (push) Has been skipped
Build & Test / Server Test (1, 4) (push) Has been skipped
Build & Test / Server Test (2, 4) (push) Has been skipped
Build & Test / Server Test (3, 4) (push) Has been skipped
Build & Test / Server Test with Elasticsearch (push) Has been skipped
Build & Test / Build @affine/electron renderer (push) Failing after 3s
Build & Test / Copilot test filter (push) Failing after 4s
Build & Test / Lint Rust (push) Has been skipped
Build & Test / Server Test with Embedded Search (push) Has been skipped
Build & Test / Server Test with Manticore Search (push) Has been skipped
Build & Test / Server E2E Test (push) Has been skipped
Build & Test / Cloud Desktop E2E Test (push) Has been skipped
Build & Test / Cloud E2E Test 1/2 (push) Has been skipped
Build & Test / Cloud E2E Test 2/2 (push) Has been skipped
Build & Test / Build Android app (push) Has been skipped
Build & Test / Test Android app (push) Has been skipped
Build & Test / Run native tests (push) Has been skipped
Build & Test / Server Copilot Api Test (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (1, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (2, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (3, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (4, 5) (push) Has been skipped
Build & Test / Frontend Copilot E2E Test (5, 5) (push) Has been skipped
Release / Canary Gate (push) Has been skipped
Build & Test / Build AFFiNE native (aarch64-apple-darwin) (push) Has been cancelled
Build & Test / Lint (push) Has been cancelled
Build & Test / Typecheck (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-apple-darwin) (push) Has been cancelled
Build & Test / Desktop Test (ubuntu-latest, linux, x64, x86_64-unknown-linux-gnu, true) (push) Has been cancelled
Build & Test / Desktop Test (windows-latest, windows, x64, x86_64-pc-windows-msvc, true) (push) Has been cancelled
Build & Test / E2E Test (1) (push) Has been cancelled
Build & Test / E2E Test (2) (push) Has been cancelled
Build & Test / E2E Test (3) (push) Has been cancelled
Build & Test / E2E Test (4) (push) Has been cancelled
Build & Test / E2E Test (5) (push) Has been cancelled
Build & Test / Build AFFiNE native (aarch64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Build AFFiNE native (x86_64-pc-windows-msvc) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, arm64, aarch64-apple-darwin, true) (push) Has been cancelled
Build & Test / Desktop Test (macos-latest, macos, x64, x86_64-apple-darwin, false) (push) Has been cancelled
Build & Test / 3, 2, 1 Launch (push) Has been cancelled
Build & Test / Build iOS app (push) Has been cancelled
Copilot Test Automatically / Setup Test (push) Failing after 1s
Release / Prepare (push) Failing after 2s
Release / Release Cloud (push) Has been skipped
Release / Release Desktop (push) Has been skipped
Release / Release Docker Image (push) Has been skipped
Release / Release Mobile (push) Has been skipped

This commit is contained in:
upstream-mirror
2026-09-16 04:01:20 +05:00
commit 702cc698a7
9990 changed files with 1073618 additions and 0 deletions

View File

@@ -0,0 +1,340 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
const connect = vi.fn();
const checkpoint = vi.fn();
const poolVacuumInto = vi.fn();
const pathExists = vi.fn();
const remove = vi.fn();
const move = vi.fn();
const realpath = vi.fn();
const copyFile = vi.fn();
const ensureDir = vi.fn();
const copy = vi.fn();
const storeWorkspaceMeta = vi.fn();
const getSpaceDBPath = vi.fn();
const getWorkspaceDBPath = vi.fn();
const getWorkspacesBasePath = vi.fn();
const docValidate = vi.fn();
const docValidateImportSchema = vi.fn();
const docVacuumInto = vi.fn();
const docSetSpaceId = vi.fn();
const sqliteValidate = vi.fn();
const sqliteValidateImportSchema = vi.fn();
const sqliteVacuumInto = vi.fn();
const sqliteClose = vi.fn();
const showOpenDialog = vi.fn();
const showSaveDialog = vi.fn();
const showItemInFolder = vi.fn(async () => undefined);
const getPath = vi.fn();
vi.doMock('nanoid', () => ({
nanoid: () => 'workspace-1',
}));
vi.doMock('@affine/native', () => {
const ValidationResult = {
MissingTables: 'MissingTables',
MissingDocIdColumn: 'MissingDocIdColumn',
MissingVersionColumn: 'MissingVersionColumn',
GeneralError: 'GeneralError',
Valid: 'Valid',
};
return {
ValidationResult,
DocStorage: class {
constructor(private readonly path: string) {}
validate() {
return docValidate(this.path);
}
validateImportSchema() {
return docValidateImportSchema(this.path);
}
vacuumInto(path: string) {
return docVacuumInto(this.path, path);
}
setSpaceId(spaceId: string) {
return docSetSpaceId(this.path, spaceId);
}
},
SqliteConnection: class {
static validate(path: string) {
return sqliteValidate(path);
}
constructor(private readonly path: string) {}
validateImportSchema() {
return sqliteValidateImportSchema(this.path);
}
vacuumInto(path: string) {
return sqliteVacuumInto(this.path, path);
}
close() {
return sqliteClose(this.path);
}
},
};
});
vi.doMock('@affine/electron/helper/nbstore', () => ({
getDocStoragePool: () => ({
connect,
checkpoint,
vacuumInto: poolVacuumInto,
}),
}));
vi.doMock('@affine/electron/helper/main-rpc', () => ({
mainRPC: {
getPath,
showItemInFolder,
showOpenDialog,
showSaveDialog,
},
}));
vi.doMock('@affine/electron/helper/workspace/meta', () => ({
getSpaceDBPath,
getWorkspaceDBPath,
getWorkspacesBasePath,
}));
vi.doMock('@affine/electron/helper/workspace', () => ({
storeWorkspaceMeta,
}));
vi.doMock('fs-extra', () => ({
default: {
pathExists,
remove,
move,
realpath,
copyFile,
ensureDir,
copy,
},
}));
afterEach(() => {
vi.clearAllMocks();
vi.resetModules();
});
describe('dialog export', () => {
test('saveDBFileAs exports a vacuumed backup instead of copying the live db', async () => {
const dbPath = '/tmp/workspace/storage.db';
const exportPath = '/tmp/export.affine';
const tempExportPath = '/tmp/export.affine.workspace-1.tmp';
const id = '@peer(local);@type(workspace);@id(workspace-1);';
pathExists.mockImplementation(async path => path === dbPath);
realpath.mockImplementation(async path => path);
getSpaceDBPath.mockResolvedValue(dbPath);
move.mockResolvedValue(undefined);
showSaveDialog.mockResolvedValue({ canceled: false, filePath: exportPath });
const { saveDBFileAs } =
await import('@affine/electron/helper/dialog/dialog');
const result = await saveDBFileAs(id, 'My Space');
expect(result).toEqual({ filePath: exportPath });
expect(connect).toHaveBeenCalledWith(id, dbPath);
expect(checkpoint).toHaveBeenCalledWith(id);
expect(poolVacuumInto).toHaveBeenCalledWith(id, tempExportPath);
expect(move).toHaveBeenCalledWith(tempExportPath, exportPath, {
overwrite: true,
});
expect(remove).not.toHaveBeenCalledWith(exportPath);
expect(copyFile).not.toHaveBeenCalled();
});
test('saveDBFileAs rejects exporting over the live database path', async () => {
const dbPath = '/tmp/workspace/storage.db';
const id = '@peer(local);@type(workspace);@id(workspace-1);';
pathExists.mockResolvedValue(false);
getSpaceDBPath.mockResolvedValue(dbPath);
showSaveDialog.mockResolvedValue({ canceled: false, filePath: dbPath });
const { saveDBFileAs } =
await import('@affine/electron/helper/dialog/dialog');
const result = await saveDBFileAs(id, 'My Space');
expect(result).toEqual({ error: 'DB_FILE_PATH_INVALID' });
expect(poolVacuumInto).not.toHaveBeenCalled();
expect(copyFile).not.toHaveBeenCalled();
});
test('saveDBFileAs rejects exporting to a symlink alias of the live database', async () => {
const dbPath = '/tmp/workspace/storage.db';
const exportPath = '/tmp/alias.affine';
const id = '@peer(local);@type(workspace);@id(workspace-1);';
pathExists.mockResolvedValue(true);
realpath.mockImplementation(async path =>
path === exportPath ? dbPath : path
);
getSpaceDBPath.mockResolvedValue(dbPath);
showSaveDialog.mockResolvedValue({ canceled: false, filePath: exportPath });
const { saveDBFileAs } =
await import('@affine/electron/helper/dialog/dialog');
const result = await saveDBFileAs(id, 'My Space');
expect(result).toEqual({ error: 'DB_FILE_PATH_INVALID' });
expect(poolVacuumInto).not.toHaveBeenCalled();
expect(move).not.toHaveBeenCalled();
});
});
describe('dialog import', () => {
test('loadDBFile validates schema and vacuums v2 imports into internal storage', async () => {
const originalPath = '/tmp/import.affine';
const internalPath = '/app/workspaces/local/workspace-1/storage.db';
pathExists.mockResolvedValue(true);
realpath.mockImplementation(async path => path);
showOpenDialog.mockResolvedValue({
canceled: false,
filePaths: [originalPath],
});
getWorkspacesBasePath.mockResolvedValue('/app/workspaces');
getSpaceDBPath.mockResolvedValue(internalPath);
docValidate.mockResolvedValue(true);
docValidateImportSchema.mockResolvedValue(true);
docVacuumInto.mockResolvedValue(undefined);
docSetSpaceId.mockResolvedValue(undefined);
ensureDir.mockResolvedValue(undefined);
const { loadDBFile } =
await import('@affine/electron/helper/dialog/dialog');
const result = await loadDBFile();
expect(result).toEqual({ workspaceId: 'workspace-1' });
expect(docValidate).toHaveBeenCalledWith(originalPath);
expect(docValidateImportSchema).toHaveBeenCalledWith(originalPath);
expect(docVacuumInto).toHaveBeenCalledWith(originalPath, internalPath);
expect(docSetSpaceId).toHaveBeenCalledWith(internalPath, 'workspace-1');
expect(copy).not.toHaveBeenCalled();
});
test('loadDBFile rejects v2 imports with unexpected schema objects', async () => {
const originalPath = '/tmp/import.affine';
pathExists.mockResolvedValue(true);
realpath.mockImplementation(async path => path);
showOpenDialog.mockResolvedValue({
canceled: false,
filePaths: [originalPath],
});
getWorkspacesBasePath.mockResolvedValue('/app/workspaces');
docValidate.mockResolvedValue(true);
docValidateImportSchema.mockResolvedValue(false);
const { loadDBFile } =
await import('@affine/electron/helper/dialog/dialog');
const result = await loadDBFile();
expect(result).toEqual({ error: 'DB_FILE_INVALID' });
expect(docVacuumInto).not.toHaveBeenCalled();
expect(copy).not.toHaveBeenCalled();
});
test('loadDBFile validates schema and vacuums v1 imports into internal storage', async () => {
const originalPath = '/tmp/import-v1.affine';
const internalPath = '/app/workspaces/workspace-1/storage.db';
pathExists.mockResolvedValue(true);
realpath.mockImplementation(async path => path);
showOpenDialog.mockResolvedValue({
canceled: false,
filePaths: [originalPath],
});
getWorkspacesBasePath.mockResolvedValue('/app/workspaces');
getWorkspaceDBPath.mockResolvedValue(internalPath);
docValidate.mockResolvedValue(false);
sqliteValidate.mockResolvedValue('Valid');
sqliteValidateImportSchema.mockResolvedValue(true);
sqliteVacuumInto.mockResolvedValue(undefined);
ensureDir.mockResolvedValue(undefined);
const { loadDBFile } =
await import('@affine/electron/helper/dialog/dialog');
const result = await loadDBFile();
expect(result).toEqual({ workspaceId: 'workspace-1' });
expect(sqliteValidate).toHaveBeenCalledWith(originalPath);
expect(sqliteValidateImportSchema).toHaveBeenCalledWith(originalPath);
expect(ensureDir).toHaveBeenCalledWith('/app/workspaces/workspace-1');
expect(sqliteVacuumInto).toHaveBeenCalledWith(originalPath, internalPath);
expect(storeWorkspaceMeta).toHaveBeenCalledWith('workspace-1', {
id: 'workspace-1',
mainDBPath: internalPath,
});
expect(sqliteClose).toHaveBeenCalledWith(originalPath);
expect(copy).not.toHaveBeenCalled();
});
test('loadDBFile closes v1 connection when schema validation fails', async () => {
const originalPath = '/tmp/import-v1-invalid.affine';
pathExists.mockResolvedValue(true);
realpath.mockImplementation(async path => path);
showOpenDialog.mockResolvedValue({
canceled: false,
filePaths: [originalPath],
});
getWorkspacesBasePath.mockResolvedValue('/app/workspaces');
docValidate.mockResolvedValue(false);
sqliteValidate.mockResolvedValue('Valid');
sqliteValidateImportSchema.mockResolvedValue(false);
const { loadDBFile } =
await import('@affine/electron/helper/dialog/dialog');
const result = await loadDBFile();
expect(result).toEqual({ error: 'DB_FILE_INVALID' });
expect(sqliteClose).toHaveBeenCalledWith(originalPath);
expect(sqliteVacuumInto).not.toHaveBeenCalled();
});
test('loadDBFile rejects normalized paths inside app data', async () => {
const selectedPath = '/tmp/import.affine';
const normalizedPath = '/app/workspaces/local/existing/storage.db';
pathExists.mockResolvedValue(true);
realpath.mockImplementation(async path => {
if (path === selectedPath) {
return normalizedPath;
}
return path;
});
showOpenDialog.mockResolvedValue({
canceled: false,
filePaths: [selectedPath],
});
getWorkspacesBasePath.mockResolvedValue('/app/workspaces');
const { loadDBFile } =
await import('@affine/electron/helper/dialog/dialog');
const result = await loadDBFile();
expect(result).toEqual({ error: 'DB_FILE_PATH_INVALID' });
expect(docValidate).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,85 @@
import path from 'node:path';
import fs from 'fs-extra';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
const { native } = vi.hoisted(() => ({
native: {
renderMermaidSvg: vi.fn(),
renderTypstSvg: vi.fn(),
},
}));
vi.mock('@affine/native', () => native);
const tmpDir = path.join(__dirname, 'tmp');
const typstFontDirA = path.join(tmpDir, 'fonts-a');
const typstFontDirB = path.join(tmpDir, 'fonts-b');
async function loadPreviewHandlers() {
vi.resetModules();
const module = await import('../../src/helper/preview');
return module.previewHandlers;
}
describe('helper preview handlers', () => {
beforeEach(async () => {
await fs.ensureDir(typstFontDirA);
await fs.ensureDir(typstFontDirB);
process.env.AFFINE_TYPST_FONT_DIRS = [
typstFontDirA,
typstFontDirB,
path.join(tmpDir, 'missing'),
].join(path.delimiter);
native.renderMermaidSvg.mockReset();
native.renderTypstSvg.mockReset();
native.renderMermaidSvg.mockReturnValue({
svg: '<svg><text>mermaid</text></svg>',
});
native.renderTypstSvg.mockReturnValue({
svg: '<svg><text>typst</text></svg>',
});
});
afterEach(async () => {
delete process.env.AFFINE_TYPST_FONT_DIRS;
await fs.remove(tmpDir);
});
test('passes mermaid request to native renderer', async () => {
const previewHandlers = await loadPreviewHandlers();
const request = { code: 'flowchart TD; A-->B' };
await previewHandlers.renderMermaidSvg(request);
expect(native.renderMermaidSvg).toHaveBeenCalledWith(request);
});
test('injects resolved fontDirs into typst requests', async () => {
const previewHandlers = await loadPreviewHandlers();
await previewHandlers.renderTypstSvg({ code: '= hello' });
const [request] = native.renderTypstSvg.mock.calls[0];
expect(request.options?.fontDirs).toEqual(
expect.arrayContaining([
path.resolve(typstFontDirA),
path.resolve(typstFontDirB),
])
);
});
test('keeps explicit typst fontDirs', async () => {
const previewHandlers = await loadPreviewHandlers();
const request = {
code: '= hello',
options: {
fontDirs: ['/tmp/custom-fonts'],
},
};
await previewHandlers.renderTypstSvg(request);
expect(native.renderTypstSvg).toHaveBeenCalledWith(request);
});
});

View File

@@ -0,0 +1,107 @@
import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, test } from 'vitest';
import {
assertPathComponent,
normalizeWorkspaceIdForPath,
resolveExistingPathInBase,
resolvePathInBase,
} from '../../src/shared/utils';
const tmpDir = path.join(os.tmpdir(), `affine-electron-utils-${randomUUID()}`);
afterEach(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
describe('path guards', () => {
test('resolvePathInBase blocks sibling-prefix escapes', () => {
const baseDir = path.join(tmpDir, 'recordings');
expect(() =>
resolvePathInBase(baseDir, '../recordings-evil/file.opus', {
label: 'directory',
})
).toThrow('Invalid directory');
});
test.runIf(process.platform !== 'win32')(
'resolveExistingPathInBase rejects symlink escapes',
async () => {
const baseDir = path.join(tmpDir, 'recordings');
const outsideDir = path.join(tmpDir, 'outside');
const outsideFile = path.join(outsideDir, 'secret.txt');
const linkPath = path.join(baseDir, '1234567890abcdef.blob');
await fs.mkdir(baseDir, { recursive: true });
await fs.mkdir(outsideDir, { recursive: true });
await fs.writeFile(outsideFile, 'secret');
await fs.symlink(outsideFile, linkPath);
await expect(
resolveExistingPathInBase(baseDir, linkPath, {
label: 'recording filepath',
})
).rejects.toThrow('Invalid recording filepath');
}
);
test('resolveExistingPathInBase falls back for missing descendants', async () => {
const baseDir = path.join(tmpDir, 'recordings');
await fs.mkdir(baseDir, { recursive: true });
const missingPath = path.join(
await fs.realpath(baseDir),
'pending',
'recording.opus'
);
await expect(
resolveExistingPathInBase(baseDir, missingPath, {
label: 'recording filepath',
})
).resolves.toBe(path.resolve(missingPath));
});
test.runIf(process.platform !== 'win32')(
'resolveExistingPathInBase preserves non-missing realpath errors',
async () => {
const baseDir = path.join(tmpDir, 'recordings');
const loopPath = path.join(baseDir, 'loop.opus');
await fs.mkdir(baseDir, { recursive: true });
await fs.symlink(path.basename(loopPath), loopPath);
await expect(
resolveExistingPathInBase(baseDir, loopPath, {
label: 'recording filepath',
})
).rejects.toMatchObject({ code: 'ELOOP' });
}
);
test.each(['../../escape', 'nested/id'])(
'assertPathComponent rejects invalid workspace id %s',
input => {
expect(() => assertPathComponent(input, 'workspace id')).toThrow(
'Invalid workspace id'
);
}
);
test.each([
{ input: 'legacy:id*with?reserved.', expected: 'legacy_id_with_reserved' },
{ input: 'safe-workspace', expected: 'safe-workspace' },
])(
'normalizeWorkspaceIdForPath maps $input to $expected on Windows',
({ input, expected }) => {
expect(normalizeWorkspaceIdForPath(input, { windows: true })).toBe(
expected
);
}
);
});

View File

@@ -0,0 +1,50 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`testing for client update > filter valid installer files > filter for platform [darwin] arch [arm64] 1`] = `
[
"affine-0.18.0-stable-macos-arm64.dmg",
"affine-0.18.0-stable-macos-arm64.zip",
"affine-0.18.0-stable-macos-x64.dmg",
"affine-0.18.0-stable-macos-x64.zip",
]
`;
exports[`testing for client update > filter valid installer files > filter for platform [darwin] arch [x64] 1`] = `
[
"affine-0.18.0-stable-macos-x64.dmg",
"affine-0.18.0-stable-macos-x64.zip",
]
`;
exports[`testing for client update > filter valid installer files > filter for platform [linux] arch [x64] 1`] = `
[
"affine-0.18.0-stable-linux-x64.appimage",
"affine-0.18.0-stable-linux-x64.deb",
"affine-0.18.0-stable-linux-x64.flatpak",
"affine-0.18.0-stable-linux-x64.zip",
]
`;
exports[`testing for client update > filter valid installer files > filter for platform [win32] arch [arm64] 1`] = `
[
"affine-0.18.0-stable-windows-arm64.nsis.exe",
]
`;
exports[`testing for client update > filter valid installer files > filter for platform [win32] arch [arm64] and is squirrel installer 1`] = `
[
"affine-0.18.0-stable-windows-arm64.exe",
]
`;
exports[`testing for client update > filter valid installer files > filter for platform [win32] arch [x64] 1`] = `
[
"affine-0.18.0-stable-windows-x64.nsis.exe",
]
`;
exports[`testing for client update > filter valid installer files > filter for platform [win32] arch [x64] and is squirrel installer 1`] = `
[
"affine-0.18.0-stable-windows-x64.exe",
]
`;

View File

@@ -0,0 +1,346 @@
import path from 'node:path';
import { beforeEach, expect, test, vi } from 'vitest';
const sessionFile = path.join('/test-user-data', 'auth-sessions.json');
const temporarySessionFile = `${sessionFile}.tmp`;
const runtime = vi.hoisted(() => ({
encryptionAvailable: true,
backend: 'unknown',
failWrite: false,
files: new Map<string, string>(),
fetch: vi.fn(),
fromPartition: vi.fn(),
rename: vi.fn(),
}));
vi.mock('node:fs/promises', () => ({
default: {
readFile: vi.fn(async (file: string) => {
const value = runtime.files.get(file);
if (value === undefined) {
throw Object.assign(new Error('not found'), { code: 'ENOENT' });
}
return value;
}),
writeFile: vi.fn(async (file: string, value: string) => {
if (runtime.failWrite) throw new Error('disk unavailable');
runtime.files.set(file, value);
}),
rename: vi.fn(async (source: string, target: string) => {
runtime.rename(source, target);
const value = runtime.files.get(source);
if (value !== undefined) runtime.files.set(target, value);
runtime.files.delete(source);
}),
rm: vi.fn(async (file: string) => {
runtime.files.delete(file);
}),
},
}));
vi.mock('electron', () => ({
app: { getPath: () => '/test-user-data' },
session: {
fromPartition: (...args: unknown[]) => {
runtime.fromPartition(...args);
return { fetch: runtime.fetch };
},
},
safeStorage: {
isEncryptionAvailable: () => runtime.encryptionAvailable,
getSelectedStorageBackend: () => runtime.backend,
encryptString: (value: string) => Buffer.from(value),
decryptString: (value: Buffer) => value.toString(),
},
}));
vi.mock('../../src/main/logger', () => ({
logger: { error: vi.fn() },
}));
import {
clearAuthSession,
executeAuthSessionRequest,
getValidAccessToken,
initializeAuthSessions,
isManagedAuthEndpoint,
normalizeEndpoint,
revokeAuthSession,
setAuthSession,
} from '../../src/main/auth/auth-session';
beforeEach(() => {
runtime.encryptionAvailable = true;
runtime.backend = 'unknown';
runtime.failWrite = false;
runtime.fetch.mockReset();
runtime.fromPartition.mockClear();
runtime.rename.mockClear();
});
test.each([
['https://AFFINE.PRO/path?query=1', 'https://affine.pro'],
['https://affine.pro:443', 'https://affine.pro'],
['http://localhost:80/path', 'http://localhost'],
['http://localhost:8080/path', 'http://localhost:8080'],
])('normalizes auth endpoint %s', (endpoint, expected) => {
expect(normalizeEndpoint(endpoint)).toBe(expected);
});
test('loads and atomically persists one encrypted token-pair record', async () => {
const endpoint = 'https://persistent.example';
const pair = tokenResponse('access-persistent', 'p', 900);
runtime.files.set(
sessionFile,
JSON.stringify({
[endpoint]: Buffer.from(
JSON.stringify({
version: 1,
tokenType: pair.tokenType,
accessToken: pair.accessToken,
accessExpiresAt: new Date(
Date.now() + pair.expiresIn * 1000
).toISOString(),
refreshToken: pair.refreshToken,
refreshExpiresAt: pair.refreshExpiresAt,
session: pair.session,
})
).toString('base64'),
})
);
expect(isManagedAuthEndpoint(endpoint)).toBe(false);
await initializeAuthSessions();
expect(isManagedAuthEndpoint(endpoint)).toBe(true);
expect(await getValidAccessToken(endpoint)).toBe('access-persistent');
await expect(setAuthSession(endpoint, pair)).resolves.toEqual({
persistent: true,
});
expect(await getValidAccessToken(endpoint)).toBe('access-persistent');
expect(runtime.rename).toHaveBeenCalledWith(
temporarySessionFile,
sessionFile
);
const file = runtime.files.get(sessionFile) ?? '';
expect(file).not.toContain(pair.refreshToken);
});
test('keeps a session in main-process memory when safeStorage is unavailable', async () => {
const endpoint = 'https://session-only.example';
await setAuthSession(endpoint, tokenResponse('old-persistent', 'o', 900));
runtime.encryptionAvailable = false;
await expect(
setAuthSession(endpoint, tokenResponse('session-access', 's', 900))
).resolves.toEqual({ persistent: false });
expect(await getValidAccessToken(endpoint)).toBe('session-access');
expect(runtime.files.get(sessionFile)).not.toContain(endpoint);
runtime.encryptionAvailable = true;
});
test('rejects Linux basic_text persistence and removes an older disk session', async () => {
const platform = vi
.spyOn(process, 'platform', 'get')
.mockReturnValue('linux');
const endpoint = 'https://basic-text.example';
await setAuthSession(endpoint, tokenResponse('old', 'o', 900));
runtime.backend = 'basic_text';
await expect(
setAuthSession(endpoint, tokenResponse('memory', 'm', 900))
).resolves.toEqual({ persistent: false });
expect(await getValidAccessToken(endpoint)).toBe('memory');
expect(runtime.files.get(sessionFile)).not.toContain(endpoint);
platform.mockRestore();
});
test('shares one refresh across concurrent main-process callers', async () => {
const endpoint = 'https://refresh.example';
await setAuthSession(endpoint, tokenResponse('expiring', 'a', 1));
runtime.fetch.mockResolvedValueOnce(
new Response(JSON.stringify(tokenResponse('fresh', 'b', 900)))
);
const tokens = await Promise.all(
Array.from({ length: 50 }, () => getValidAccessToken(endpoint, 120_000))
);
expect(tokens.every(token => token === 'fresh')).toBe(true);
expect(runtime.fetch).toHaveBeenCalledTimes(1);
expect(runtime.fromPartition).toHaveBeenCalledWith('affine-auth-transport', {
cache: false,
});
});
test('preserves credentials for unknown refresh errors', async () => {
const endpoint = 'https://unknown-error.example';
await setAuthSession(endpoint, tokenResponse('still-valid', 'u', 900));
runtime.fetch.mockImplementation(
async () =>
new Response(JSON.stringify({ code: 'UNKNOWN_SELF_HOSTED_ERROR' }), {
status: 401,
})
);
await expect(getValidAccessToken(endpoint, 1_000_000)).rejects.toMatchObject({
code: 'AUTH_SESSION_TEMPORARILY_UNAVAILABLE',
transient: true,
});
await expect(getValidAccessToken(endpoint, 0)).resolves.toBe('still-valid');
});
test('clears credentials only for an allowlisted permanent refresh error', async () => {
const endpoint = 'https://permanent-error.example';
await setAuthSession(endpoint, tokenResponse('expired', 'e', 1));
runtime.fetch.mockResolvedValueOnce(
new Response(JSON.stringify({ code: 'AUTH_SESSION_REVOKED' }), {
status: 401,
})
);
await expect(getValidAccessToken(endpoint, 120_000)).resolves.toBeNull();
await expect(getValidAccessToken(endpoint, 0)).resolves.toBeNull();
expect(runtime.files.get(sessionFile)).not.toContain(endpoint);
});
test('cleans a decrypted record that does not match the token-pair schema', async () => {
const endpoint = 'https://corrupt.example';
runtime.files.set(
sessionFile,
JSON.stringify({
[endpoint]: Buffer.from(JSON.stringify({ token: 'legacy' })).toString(
'base64'
),
})
);
await expect(getValidAccessToken(endpoint)).resolves.toBeNull();
expect(runtime.files.get(sessionFile)).not.toContain(endpoint);
});
test('recovers an unreadable session file on the next atomic write', async () => {
runtime.files.set(sessionFile, '{not-json');
const endpoint = 'https://file-corruption.example';
await expect(getValidAccessToken(endpoint)).resolves.toBeNull();
await setAuthSession(endpoint, tokenResponse('recovered', 'c', 900));
expect(JSON.parse(runtime.files.get(sessionFile)!)).toHaveProperty(endpoint);
await expect(getValidAccessToken(endpoint)).resolves.toBe('recovered');
});
test('does not publish a rotated pair until an atomic save succeeds', async () => {
const endpoint = 'https://save-failure.example';
await setAuthSession(endpoint, tokenResponse('old', 'a', 1));
runtime.fetch.mockResolvedValueOnce(
new Response(JSON.stringify(tokenResponse('rotated', 'b', 900)))
);
runtime.failWrite = true;
await expect(getValidAccessToken(endpoint, 120_000)).rejects.toMatchObject({
code: 'AUTH_TOKEN_STORAGE_UNAVAILABLE',
});
runtime.failWrite = false;
await expect(getValidAccessToken(endpoint, 120_000)).resolves.toBe('rotated');
expect(runtime.fetch).toHaveBeenCalledTimes(1);
});
test('main replaces renderer bearer and strips it after local clear', async () => {
const endpoint = 'https://owner.example';
await setAuthSession(endpoint, tokenResponse('main-token', 'm', 900));
const execute = vi.fn(async () => new Response('{}'));
await executeAuthSessionRequest(
new Request(`${endpoint}/graphql`, {
headers: { Authorization: 'Bearer renderer-stale' },
}),
`${endpoint}/graphql`,
execute
);
expect(execute.mock.calls[0]?.[0].headers.get('Authorization')).toBe(
'Bearer main-token'
);
await clearAuthSession(endpoint, 'test-clear');
await executeAuthSessionRequest(
new Request(`${endpoint}/graphql`, {
headers: { Authorization: 'Bearer renderer-stale' },
}),
`${endpoint}/graphql`,
execute
);
expect(execute.mock.calls[1]?.[0].headers.get('Authorization')).toBeNull();
});
test.each([
{
code: 'ACCESS_TOKEN_EXPIRED',
expectedRequests: 2,
method: 'POST',
},
{ code: 'FORBIDDEN', expectedRequests: 1, method: 'PUT' },
])('replays a protocol request once for $code only', async item => {
const endpoint = `https://${item.code.toLowerCase()}.example`;
await setAuthSession(endpoint, tokenResponse('initial', 'i', 900));
runtime.fetch.mockResolvedValueOnce(
new Response(JSON.stringify(tokenResponse('refreshed', 'f', 900)))
);
const execute = vi
.fn<(request: Request) => Promise<Response>>()
.mockResolvedValueOnce(
new Response(JSON.stringify({ code: item.code }), { status: 401 })
)
.mockResolvedValueOnce(new Response('{}'));
await executeAuthSessionRequest(
new Request(`${endpoint}/api/test`, {
method: item.method,
body: JSON.stringify({ value: item.code }),
duplex: 'half',
}),
`${endpoint}/api/test`,
execute
);
expect(execute).toHaveBeenCalledTimes(item.expectedRequests);
expect(runtime.fetch).toHaveBeenCalledTimes(
item.code === 'ACCESS_TOKEN_EXPIRED' ? 1 : 0
);
for (const [request] of execute.mock.calls) {
await expect(request.text()).resolves.toBe(
JSON.stringify({ value: item.code })
);
}
});
test('clears locally before revoking without exposing refresh token over IPC', async () => {
const endpoint = 'https://revoke.example';
const pair = tokenResponse('revoke-access', 'r', 900);
await setAuthSession(endpoint, pair);
runtime.fetch.mockResolvedValueOnce(new Response('{}'));
await revokeAuthSession(endpoint);
expect(await getValidAccessToken(endpoint)).toBeNull();
const request = runtime.fetch.mock.calls.at(-1)?.[1] as RequestInit;
expect(request.body).toBe(
JSON.stringify({ refreshToken: pair.refreshToken })
);
});
function tokenResponse(accessToken: string, seed: string, expiresIn: number) {
return {
tokenType: 'Bearer' as const,
accessToken,
expiresIn,
refreshToken: `aff_rt_v1.${seed.repeat(24)}.${seed.repeat(43)}`,
refreshExpiresAt: '2030-01-01T00:00:00.000Z',
session: {
id: '00000000-0000-4000-8000-000000000001',
absoluteExpiresAt: '2031-01-01T00:00:00.000Z',
},
};
}

View File

@@ -0,0 +1,314 @@
import os from 'node:os';
import path from 'node:path';
import fs from 'fs-extra';
import {
afterEach,
beforeAll,
beforeEach,
describe,
expect,
test,
vi,
} from 'vitest';
const electronMock = vi.hoisted(() => ({
tmpDir: '',
appOn: vi.fn(),
isEncryptionAvailable: vi.fn(() => true),
encryptString: vi.fn((value: string) => Buffer.from(value, 'utf-8')),
decryptString: vi.fn((value: Buffer) => value.toString('utf-8')),
}));
let disposeWorkspaceByokStorage: (() => void) | undefined;
vi.mock('electron', () => ({
app: {
getPath: () => electronMock.tmpDir,
on: electronMock.appOn,
},
safeStorage: {
isEncryptionAvailable: electronMock.isEncryptionAvailable,
encryptString: electronMock.encryptString,
decryptString: electronMock.decryptString,
},
}));
vi.mock('../../src/main/logger', () => ({
logger: {
error: vi.fn(),
},
}));
// Warm the handler module's transform once so the first per-test dynamic
// import doesn't race the default 60s test timeout on loaded CI shards, where
// cold-transforming the heavy `@toeverything/infra` graph can starve.
beforeAll(async () => {
await import('@affine/electron/main/byok-storage/handlers');
}, 120_000);
beforeEach(async () => {
vi.useRealTimers();
vi.resetModules();
electronMock.appOn.mockReset();
electronMock.isEncryptionAvailable.mockReset().mockReturnValue(true);
electronMock.encryptString
.mockReset()
.mockImplementation((value: string) => Buffer.from(value, 'utf-8'));
electronMock.decryptString
.mockReset()
.mockImplementation((value: Buffer) => value.toString('utf-8'));
disposeWorkspaceByokStorage = undefined;
electronMock.tmpDir = await fs.mkdtemp(
path.join(os.tmpdir(), 'affine-byok-storage-')
);
});
afterEach(async () => {
disposeWorkspaceByokStorage?.();
disposeWorkspaceByokStorage = undefined;
vi.resetModules();
if (electronMock.tmpDir) {
await fs.remove(electronMock.tmpDir);
}
electronMock.tmpDir = '';
});
describe('byok storage handlers', () => {
const definition = {
endpoint: { kind: 'provider_default' },
models: [
{
modelId: 'model-1',
enabled: true,
capabilities: [
{
input: ['text'],
output: ['text'],
features: [],
attachmentKinds: [],
attachmentSources: [],
},
],
},
],
};
test('stores encrypted local keys and keeps lease providers sorted', async () => {
const { byokStorageHandlers, disposeWorkspaceByokStorage: dispose } =
await import('@affine/electron/main/byok-storage/handlers');
disposeWorkspaceByokStorage = dispose;
const ipcEvent = undefined;
await byokStorageHandlers.upsertWorkspaceKey(ipcEvent, 'workspace-1', {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI',
credential: 'sk-openai',
definition,
sortOrder: 1,
});
await byokStorageHandlers.upsertWorkspaceKey(ipcEvent, 'workspace-1', {
id: 'local-gemini',
provider: 'gemini',
name: 'Gemini',
credential: 'sk-gemini',
definition,
sortOrder: 0,
});
const list = await byokStorageHandlers.listWorkspaceKeys(
ipcEvent,
'workspace-1'
);
expect(list.map(key => key.id)).toEqual(['local-gemini', 'local-openai']);
expect(JSON.stringify(list)).not.toContain('sk-openai');
const reordered = await byokStorageHandlers.reorderWorkspaceKeys(
ipcEvent,
'workspace-1',
['local-openai', 'local-gemini']
);
expect(reordered.map(key => key.id)).toEqual([
'local-openai',
'local-gemini',
]);
const leaseProviders = await byokStorageHandlers.getWorkspaceLeaseProviders(
ipcEvent,
'workspace-1'
);
expect(leaseProviders.map(key => key.credential)).toEqual([
'sk-openai',
'sk-gemini',
]);
await byokStorageHandlers.clearWorkspaceKeys(ipcEvent, 'workspace-1');
await expect(
byokStorageHandlers.listWorkspaceKeys(ipcEvent, 'workspace-1')
).resolves.toEqual([]);
});
test('does not write local keys when secure storage is unavailable', async () => {
electronMock.isEncryptionAvailable.mockReturnValue(false);
const { byokStorageHandlers, disposeWorkspaceByokStorage: dispose } =
await import('@affine/electron/main/byok-storage/handlers');
disposeWorkspaceByokStorage = dispose;
const ipcEvent = undefined;
await expect(byokStorageHandlers.isSupported()).resolves.toBe(false);
await expect(
byokStorageHandlers.upsertWorkspaceKey(ipcEvent, 'workspace-1', {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI',
credential: 'sk-openai',
definition,
})
).rejects.toThrow('Secure BYOK key storage is not available.');
expect(electronMock.encryptString).not.toHaveBeenCalled();
});
test.each([
[
'custom endpoint without URL',
{
...definition,
endpoint: { kind: 'openai_compatible', dialect: 'responses' },
},
],
[
'unsupported endpoint protocol',
{
...definition,
endpoint: {
kind: 'openai_compatible',
url: 'file:///tmp/api',
dialect: 'responses',
},
},
],
[
'malformed capability object',
{
...definition,
models: [{ ...definition.models[0], capabilities: [{}] }],
},
],
[
'unknown capability value',
{
...definition,
models: [
{
...definition.models[0],
capabilities: [
{ ...definition.models[0].capabilities[0], input: ['video'] },
],
},
],
},
],
])('rejects %s from IPC input', async (_name, malformedDefinition) => {
const { byokStorageHandlers, disposeWorkspaceByokStorage: dispose } =
await import('@affine/electron/main/byok-storage/handlers');
disposeWorkspaceByokStorage = dispose;
await expect(
byokStorageHandlers.upsertWorkspaceKey(undefined, 'workspace-1', {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI',
credential: 'sk-openai',
definition: malformedDefinition as typeof definition,
})
).rejects.toThrow('Invalid BYOK key.');
expect(electronMock.encryptString).not.toHaveBeenCalled();
});
test('preserves existing local key fields during partial updates', async () => {
const { byokStorageHandlers, disposeWorkspaceByokStorage: dispose } =
await import('@affine/electron/main/byok-storage/handlers');
disposeWorkspaceByokStorage = dispose;
const ipcEvent = undefined;
await byokStorageHandlers.upsertWorkspaceKey(ipcEvent, 'workspace-1', {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI',
description: 'Primary key',
credential: 'sk-openai',
definition: {
...definition,
endpoint: {
kind: 'openai_compatible',
url: 'https://api.openai.example/v1',
dialect: 'responses',
},
},
sortOrder: 4,
enabled: false,
});
await byokStorageHandlers.upsertWorkspaceKey(ipcEvent, 'workspace-1', {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI renamed',
credential: 'sk-openai-next',
});
const [publicKey] = await byokStorageHandlers.listWorkspaceKeys(
ipcEvent,
'workspace-1'
);
expect(publicKey).toMatchObject({
id: 'local-openai',
name: 'OpenAI renamed',
description: 'Primary key',
definition: {
...definition,
endpoint: {
kind: 'openai_compatible',
url: 'https://api.openai.example/v1',
dialect: 'responses',
},
},
sortOrder: 4,
enabled: false,
});
const [leaseProvider] =
await byokStorageHandlers.getWorkspaceLeaseProviders(
ipcEvent,
'workspace-1'
);
expect(leaseProvider).toBeUndefined();
await byokStorageHandlers.upsertWorkspaceKey(ipcEvent, 'workspace-1', {
id: 'local-openai',
provider: 'openai',
name: 'OpenAI renamed again',
enabled: true,
});
const [enabledLeaseProvider] =
await byokStorageHandlers.getWorkspaceLeaseProviders(
ipcEvent,
'workspace-1'
);
expect(enabledLeaseProvider).toMatchObject({
name: 'OpenAI renamed again',
credential: 'sk-openai-next',
definition: {
...definition,
endpoint: {
kind: 'openai_compatible',
url: 'https://api.openai.example/v1',
dialect: 'responses',
},
},
sortOrder: 4,
enabled: true,
});
});
});

View File

@@ -0,0 +1,75 @@
[
{
"url": "https://github.com/toeverything/AFFiNE/releases/tag/v0.16.3-beta.2",
"name": "0.16.3-beta.2",
"tag_name": "v0.16.3-beta.2",
"published_at": "2024-08-14T06:56:25Z",
"assets": [
{
"name": "affine-0.16.3-beta.2-beta-linux-x64.appimage",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-linux-x64.appimage",
"size": 178308288
},
{
"name": "affine-0.16.3-beta.2-beta-linux-x64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-linux-x64.zip",
"size": 176402697
},
{
"name": "affine-0.16.3-beta.2-beta-macos-arm64.dmg",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-macos-arm64.dmg",
"size": 168063426
},
{
"name": "affine-0.16.3-beta.2-beta-macos-arm64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-macos-arm64.zip",
"size": 167528680
},
{
"name": "affine-0.16.3-beta.2-beta-macos-x64.dmg",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-macos-x64.dmg",
"size": 175049454
},
{
"name": "affine-0.16.3-beta.2-beta-macos-x64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-macos-x64.zip",
"size": 174740492
},
{
"name": "affine-0.16.3-beta.2-beta-windows-x64.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-windows-x64.exe",
"size": 177771240
},
{
"name": "affine-0.16.3-beta.2-beta-windows-x64.nsis.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/affine-0.16.3-beta.2-beta-windows-x64.nsis.exe",
"size": 130309240
},
{
"name": "codecov.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/codecov.yml",
"size": 91
},
{
"name": "latest-linux.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/latest-linux.yml",
"size": 561
},
{
"name": "latest-mac.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/latest-mac.yml",
"size": 897
},
{
"name": "latest.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/latest.yml",
"size": 562
},
{
"name": "web-static.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.16.3-beta.2/web-static.zip",
"size": 61990155
}
]
}
]

View File

@@ -0,0 +1,85 @@
[
{
"url": "https://github.com/toeverything/AFFiNE/releases/tag/v0.17.0-canary.7",
"name": "0.17.0-canary.7",
"tag_name": "v0.17.0-canary.7",
"published_at": "2024-08-29T08:20:54Z",
"assets": [
{
"name": "affine-0.17.0-canary.7-canary-linux-x64.appimage",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-linux-x64.appimage",
"size": 181990592
},
{
"name": "affine-0.17.0-canary.7-canary-linux-x64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-linux-x64.zip",
"size": 180105256
},
{
"name": "affine-0.17.0-canary.7-canary-macos-arm64.dmg",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-macos-arm64.dmg",
"size": 170556866
},
{
"name": "affine-0.17.0-canary.7-canary-macos-arm64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-macos-arm64.zip",
"size": 170382513
},
{
"name": "affine-0.17.0-canary.7-canary-macos-x64.dmg",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-macos-x64.dmg",
"size": 176815834
},
{
"name": "affine-0.17.0-canary.7-canary-macos-x64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-macos-x64.zip",
"size": 176948223
},
{
"name": "affine-0.17.0-canary.7-canary-windows-x64.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-windows-x64.exe",
"size": 182557416
},
{
"name": "affine-0.17.0-canary.7-canary-windows-x64.nsis.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-windows-x64.nsis.exe",
"size": 133493672
},
{
"name": "affine-0.17.0-canary.7-canary-windows-arm64.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-windows-arm64.exe",
"size": 182557416
},
{
"name": "affine-0.17.0-canary.7-canary-windows-arm64.nsis.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/affine-0.17.0-canary.7-canary-windows-arm64.nsis.exe",
"size": 133493672
},
{
"name": "codecov.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/codecov.yml",
"size": 91
},
{
"name": "latest-linux.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/latest-linux.yml",
"size": 575
},
{
"name": "latest-mac.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/latest-mac.yml",
"size": 919
},
{
"name": "latest.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/latest.yml",
"size": 576
},
{
"name": "web-static.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.17.0-canary.7/web-static.zip",
"size": 61555023
}
]
}
]

View File

@@ -0,0 +1,75 @@
[
{
"url": "https://github.com/toeverything/AFFiNE/releases/tag/v0.18.0",
"name": "0.18.0",
"tag_name": "v0.18.0",
"published_at": "2024-11-13T07:43:22Z",
"assets": [
{
"name": "affine-0.18.0-stable-linux-x64.appimage",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-linux-x64.appimage",
"size": 178308288
},
{
"name": "affine-0.18.0-stable-linux-x64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-linux-x64.zip",
"size": 176405078
},
{
"name": "affine-0.18.0-stable-macos-arm64.dmg",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-macos-arm64.dmg",
"size": 168093091
},
{
"name": "affine-0.18.0-stable-macos-arm64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-macos-arm64.zip",
"size": 167540517
},
{
"name": "affine-0.18.0-stable-macos-x64.dmg",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-macos-x64.dmg",
"size": 175029125
},
{
"name": "affine-0.18.0-stable-macos-x64.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-macos-x64.zip",
"size": 174752343
},
{
"name": "affine-0.18.0-stable-windows-x64.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-windows-x64.exe",
"size": 177757416
},
{
"name": "affine-0.18.0-stable-windows-x64.nsis.exe",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/affine-0.18.0-stable-windows-x64.nsis.exe",
"size": 130302976
},
{
"name": "codecov.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/codecov.yml",
"size": 91
},
{
"name": "latest-linux.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/latest-linux.yml",
"size": 539
},
{
"name": "latest-mac.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/latest-mac.yml",
"size": 865
},
{
"name": "latest.yml",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/latest.yml",
"size": 540
},
{
"name": "web-static.zip",
"url": "https://github.com/toeverything/AFFiNE/releases/download/v0.18.0/web-static.zip",
"size": 61989498
}
]
}
]

View File

@@ -0,0 +1,11 @@
version: 0.16.3-beta.2
files:
- url: affine-0.16.3-beta.2-beta-linux-x64.appimage
sha512: munCzfD0tOky2MRZVVu+/JCCMrQ4C/EcOSxkNXrEVwK0aoeYo3Q0H1Cm/KJ+7mZ2yMfxctdPH0KGfHRL0tNENg==
size: 178308288
- url: affine-0.16.3-beta.2-beta-linux-x64.zip
sha512: 6emy8f8QrhrAdNxOfHj9PSbWtRXI/LocvpsckrbqrYIi7sU12GmmS0dI2SCxvDBwYTDSoC4mh0erfzUeDSLAEg==
size: 176402697
path: affine-0.16.3-beta.2-beta-linux-x64.appimage
sha512: munCzfD0tOky2MRZVVu+/JCCMrQ4C/EcOSxkNXrEVwK0aoeYo3Q0H1Cm/KJ+7mZ2yMfxctdPH0KGfHRL0tNENg==
releaseDate: 2024-08-14T06:56:24.609Z

View File

@@ -0,0 +1,17 @@
version: 0.16.3-beta.2
files:
- url: affine-0.16.3-beta.2-beta-macos-arm64.dmg
sha512: 5sR2TXAV+hgMOvplG2CobW5VSsrGXsAoZmgWqs7uEpf491XoYkUFl5iXQZaL23xi0HpuGkSS33jSZ/b7pwy0Hg==
size: 168063426
- url: affine-0.16.3-beta.2-beta-macos-arm64.zip
sha512: aI/q3DgyORjCNLxrtsT7W1KoAcuaxUT0AY0QtwnRjtMYiJYV/s4aTQtGFISDEdHcU9Vy+mS8ZcZ6yRVCksdKAg==
size: 167528680
- url: affine-0.16.3-beta.2-beta-macos-x64.dmg
sha512: P8JoSRP5tu2fpQb/EwdV6OSPNx9lEj1NT8iAZhawgeCVLaWokMMVkcsqyRYi7vX25Hf7eegvxF5LNpYzUsfKQQ==
size: 175049454
- url: affine-0.16.3-beta.2-beta-macos-x64.zip
sha512: gpzlGq0ucZUeJOZi6h/cIFRpvIhGJ5qYmWkrD6ncMgSJQOVWQapfFOrQrmU7SCwtE92pfRUcrZeH3g9cNrJDSQ==
size: 174740492
path: affine-0.16.3-beta.2-beta-macos-arm64.dmg
sha512: 5sR2TXAV+hgMOvplG2CobW5VSsrGXsAoZmgWqs7uEpf491XoYkUFl5iXQZaL23xi0HpuGkSS33jSZ/b7pwy0Hg==
releaseDate: 2024-08-14T06:56:23.981Z

View File

@@ -0,0 +1,11 @@
version: 0.16.3-beta.2
files:
- url: affine-0.16.3-beta.2-beta-windows-x64.exe
sha512: iHiIF5Swrgz6RfL/Xf9KFZsmFggGFWtSrkj7IUJUt69Z+gxQQp2dO4wrQ4uaZmiqMVr+8Op++oeczMhcjXGPHw==
size: 177771240
- url: affine-0.16.3-beta.2-beta-windows-x64.nsis.exe
sha512: 5437aZddjbgzwGWsj/nxgepS2jBM/WB561DNz3XXA5sTtqPVafMvEmcbE1KE86JZTpAAJHcJheSwjxdYOL/Lgw==
size: 130309240
path: affine-0.16.3-beta.2-beta-windows-x64.exe
sha512: iHiIF5Swrgz6RfL/Xf9KFZsmFggGFWtSrkj7IUJUt69Z+gxQQp2dO4wrQ4uaZmiqMVr+8Op++oeczMhcjXGPHw==
releaseDate: 2024-08-14T06:56:22.750Z

View File

@@ -0,0 +1,15 @@
version: 0.17.0-canary.7
files:
- url: affine-0.17.0-canary.7-canary-linux-x64.appimage
sha512: qspZkDlItrHu02vSItbjc3I+t4FcOiHOzGt0Ap6IeZEFKal+hoOh4WIcUN16dlS/OoFm+is8yPBHqN/70xhWKA==
size: 181990592
- url: affine-0.17.0-canary.7-canary-linux-x64.deb
sha512: fom2iuMiPUlnHAGJhQdAnWJwMggK4rloNkiWqH8ZHF1Q09oturgSMGgkUEWZWXsZPpORt545eYNv5Zg9aff8yQ==
size: 180105256
- url: affine-0.17.0-canary.7-canary-linux-x64.flatpak
sha512: fom2iuMiPUlnHAGJhQdAnWJwMggK4rloNkiWqH8ZHF1Q09oturgSMGgkUEWZWXsZPpORt545eYNv5Zg9aff8yQ==
size: 180105256
- url: affine-0.17.0-canary.7-canary-linux-x64.zip
sha512: fom2iuMiPUlnHAGJhQdAnWJwMggK4rloNkiWqH8ZHF1Q09oturgSMGgkUEWZWXsZPpORt545eYNv5Zg9aff8yQ==
size: 180105256
releaseDate: 2024-08-29T08:20:53.453Z

View File

@@ -0,0 +1,15 @@
version: 0.17.0-canary.7
files:
- url: affine-0.17.0-canary.7-canary-macos-arm64.dmg
sha512: Tdy7dgrCHP95PjsZBt1evxUk7DUkn+JpseBQj1Gz60MmcsFx+0NtJvofZbUcsLFiS0IC32JM/szHlHiNGEznrQ==
size: 170556866
- url: affine-0.17.0-canary.7-canary-macos-arm64.zip
sha512: pmYD0B5Z9hrzgjcHmRCKnNawoPJiO5r1RjBBZi+THVL3TyKXzpJBr9HTNQkjYnQYgqHX4q2eoONsDNCIoqTeBA==
size: 170382513
- url: affine-0.17.0-canary.7-canary-macos-x64.dmg
sha512: k4a4GUmy/6MmSc1xVGJNeNCCtYylWWSRcfDoZA+syUhZFY6x3xrOft972ONsiRrJukXWlKrFmVTwoW68Ywe49A==
size: 176815834
- url: affine-0.17.0-canary.7-canary-macos-x64.zip
sha512: PL24krtjeiQY53F7OuS+hh8EZP3YpbLle0JboXiddSrulypxzBRquOCCinNW88Kg8ZJbOrfTkxaNOHpOAVfeaQ==
size: 176948223
releaseDate: 2024-08-29T08:20:52.810Z

View File

@@ -0,0 +1,15 @@
version: 0.17.0-canary.7
files:
- url: affine-0.17.0-canary.7-canary-windows-x64.exe
sha512: cF47Wcu69PXyMVswSzrdNktNO2lqkjsyJ/HQr2qWjFPuIJfcad9QDTfOyCVsMCV6KGUSSeFiTHyObWgKd6z2DQ==
size: 182557416
- url: affine-0.17.0-canary.7-canary-windows-x64.nsis.exe
sha512: ztugqKwPpxDDSK1OpzUPkGvL8wLXwg9rh985bs9ZvxydY037yKBAZOk96PPtow2qqRb5/9Xn8MuGrWgchqXkVg==
size: 133493672
- url: affine-0.17.0-canary.7-canary-windows-arm64.exe
sha512: cF47Wcu69PXyMVswSzrdNktNO2lqkjsyJ/HQr2qWjFPuIJfcad9QDTfOyCVsMCV6KGUSSeFiTHyObWgKd6z2DQ==
size: 182557416
- url: affine-0.17.0-canary.7-canary-windows-arm64.nsis.exe
sha512: ztugqKwPpxDDSK1OpzUPkGvL8wLXwg9rh985bs9ZvxydY037yKBAZOk96PPtow2qqRb5/9Xn8MuGrWgchqXkVg==
size: 133493672
releaseDate: 2024-08-29T08:20:51.573Z

View File

@@ -0,0 +1,39 @@
version: 0.18.0
files:
- url: affine-0.18.0-stable-windows-x64.exe
sha512: cF47Wcu69PXyMVswSzrdNktNO2lqkjsyJ/HQr2qWjFPuIJfcad9QDTfOyCVsMCV6KGUSSeFiTHyObWgKd6z2DQ==
size: 182557416
- url: affine-0.18.0-stable-windows-x64.nsis.exe
sha512: ztugqKwPpxDDSK1OpzUPkGvL8wLXwg9rh985bs9ZvxydY037yKBAZOk96PPtow2qqRb5/9Xn8MuGrWgchqXkVg==
size: 133493672
- url: affine-0.18.0-stable-windows-arm64.exe
sha512: cF47Wcu69PXyMVswSzrdNktNO2lqkjsyJ/HQr2qWjFPuIJfcad9QDTfOyCVsMCV6KGUSSeFiTHyObWgKd6z2DQ==
size: 182557416
- url: affine-0.18.0-stable-windows-arm64.nsis.exe
sha512: ztugqKwPpxDDSK1OpzUPkGvL8wLXwg9rh985bs9ZvxydY037yKBAZOk96PPtow2qqRb5/9Xn8MuGrWgchqXkVg==
size: 133493672
- url: affine-0.18.0-stable-linux-x64.appimage
sha512: qspZkDlItrHu02vSItbjc3I+t4FcOiHOzGt0Ap6IeZEFKal+hoOh4WIcUN16dlS/OoFm+is8yPBHqN/70xhWKA==
size: 181990592
- url: affine-0.18.0-stable-linux-x64.deb
sha512: fom2iuMiPUlnHAGJhQdAnWJwMggK4rloNkiWqH8ZHF1Q09oturgSMGgkUEWZWXsZPpORt545eYNv5Zg9aff8yQ==
size: 180105256
- url: affine-0.18.0-stable-linux-x64.flatpak
sha512: fom2iuMiPUlnHAGJhQdAnWJwMggK4rloNkiWqH8ZHF1Q09oturgSMGgkUEWZWXsZPpORt545eYNv5Zg9aff8yQ==
size: 180105256
- url: affine-0.18.0-stable-linux-x64.zip
sha512: fom2iuMiPUlnHAGJhQdAnWJwMggK4rloNkiWqH8ZHF1Q09oturgSMGgkUEWZWXsZPpORt545eYNv5Zg9aff8yQ==
size: 180105256
- url: affine-0.18.0-stable-macos-arm64.dmg
sha512: Tdy7dgrCHP95PjsZBt1evxUk7DUkn+JpseBQj1Gz60MmcsFx+0NtJvofZbUcsLFiS0IC32JM/szHlHiNGEznrQ==
size: 170556866
- url: affine-0.18.0-stable-macos-arm64.zip
sha512: pmYD0B5Z9hrzgjcHmRCKnNawoPJiO5r1RjBBZi+THVL3TyKXzpJBr9HTNQkjYnQYgqHX4q2eoONsDNCIoqTeBA==
size: 170382513
- url: affine-0.18.0-stable-macos-x64.dmg
sha512: k4a4GUmy/6MmSc1xVGJNeNCCtYylWWSRcfDoZA+syUhZFY6x3xrOft972ONsiRrJukXWlKrFmVTwoW68Ywe49A==
size: 176815834
- url: affine-0.18.0-stable-macos-x64.zip
sha512: PL24krtjeiQY53F7OuS+hh8EZP3YpbLle0JboXiddSrulypxzBRquOCCinNW88Kg8ZJbOrfTkxaNOHpOAVfeaQ==
size: 176948223
releaseDate: 2024-08-29T08:20:51.573Z

View File

@@ -0,0 +1,34 @@
import type { AppAdapter } from 'electron-updater/out/AppAdapter';
/**
* For testing and same as:
* https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/ElectronAppAdapter.ts
*/
export class MockedAppAdapter implements AppAdapter {
version: string;
name = 'AFFiNE-testing';
isPackaged = true;
appUpdateConfigPath = '';
userDataPath = '';
baseCachePath = '';
constructor(version: string) {
this.version = version;
}
whenReady() {
return Promise.resolve();
}
relaunch() {
return;
}
quit() {
return;
}
onQuit(_handler: (exitCode: number) => void) {
return;
}
}

View File

@@ -0,0 +1,26 @@
import http from 'node:https';
import { HttpExecutor } from 'builder-util-runtime';
import type { ClientRequest } from 'electron';
/**
* For testing and same as:
* https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/electronHttpExecutor.ts
*/
export class MockedHttpExecutor extends HttpExecutor<ClientRequest> {
createRequest(
options: any,
callback: (response: any) => void
): ClientRequest {
if (options.headers && options.headers.Host) {
// set host value from headers.Host
options.host = options.headers.Host;
// remove header property 'Host', if not removed causes net::ERR_INVALID_ARGUMENT exception
delete options.headers.Host;
}
const request = http.request(options);
request.on('response', callback);
return request as unknown as ClientRequest;
}
}

View File

@@ -0,0 +1,3 @@
export * from './app-adapter';
export * from './http-executor';
export * from './updater';

View File

@@ -0,0 +1,39 @@
import 'electron-updater'; // Prevent BaseUpdater is undefined.
import { randomBytes } from 'node:crypto';
import type { AllPublishOptions } from 'builder-util-runtime';
import { UUID } from 'builder-util-runtime';
import type { AppAdapter } from 'electron-updater/out/AppAdapter';
import type { DownloadUpdateOptions } from 'electron-updater/out/AppUpdater';
import type { InstallOptions } from 'electron-updater/out/BaseUpdater';
import { BaseUpdater } from 'electron-updater/out/BaseUpdater';
import { MockedHttpExecutor } from './http-executor';
/**
* For testing, like:
* https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/MacUpdater.ts
*/
export class MockedUpdater extends BaseUpdater {
httpExecutor: MockedHttpExecutor;
constructor(options?: AllPublishOptions | null, app?: AppAdapter) {
super(options, app);
this.httpExecutor = new MockedHttpExecutor();
Object.assign(this, {
getOrCreateStagingUserId: () => {
const id = UUID.v5(randomBytes(4096), UUID.OID);
return id;
},
});
}
doInstall(_options: InstallOptions) {
return true;
}
doDownloadUpdate(_options: DownloadUpdateOptions): Promise<string[]> {
return Promise.resolve([]);
}
}

View File

@@ -0,0 +1,417 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
const storageState = new Map<string, unknown>();
vi.mock('../../src/main/logger', () => ({
logger: {
error: vi.fn(),
info: vi.fn(),
},
}));
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
storageState.clear();
vi.doMock('../../src/main/shared-storage/storage', () => ({
globalStateStorage: {
get: (key: string) => storageState.get(key),
set: (key: string, value: unknown) => {
storageState.set(key, value);
},
},
}));
});
afterEach(() => {
vi.useRealTimers();
});
async function createCoordinator(controllerOverrides?: {
startRecording?: ReturnType<typeof vi.fn>;
stopRecording?: ReturnType<typeof vi.fn>;
abortRecording?: ReturnType<typeof vi.fn>;
}) {
const { RecordingCoordinator } =
await import('../../src/main/recording/coordinator');
const controller = {
startRecording: vi.fn(),
stopRecording: vi.fn(),
abortRecording: vi.fn(),
...controllerOverrides,
};
return {
coordinator: new RecordingCoordinator(
'/tmp',
async filepath => filepath,
async () => controller
),
controller,
};
}
describe('RecordingCoordinator', () => {
test('disabling can await native abort before allowing another start', async () => {
const startRecording = vi.fn().mockResolvedValue({
id: 'native-1',
filepath: '/tmp/0.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 123,
});
const stopRecording = vi.fn();
let releaseAbort!: () => void;
const abortRecording = vi.fn(
() =>
new Promise<void>(resolve => {
releaseAbort = resolve;
})
);
const { coordinator } = await createCoordinator({
startRecording,
stopRecording,
abortRecording,
});
await coordinator.start();
const abortPromise = coordinator.abortActive();
await Promise.resolve();
expect(startRecording).toHaveBeenCalledTimes(1);
expect(abortRecording).toHaveBeenCalledWith('native-1');
releaseAbort();
await abortPromise;
await coordinator.start();
expect(startRecording).toHaveBeenCalledTimes(2);
});
test('claiming an import binds it to a workspace and stable doc id', async () => {
storageState.set('recordingJobs:v2', [
{
id: 7,
phase: 'recorded',
appName: 'Zoom',
startTime: 1000,
createdAt: 1,
updatedAt: 1,
artifact: {
filepath: '/tmp/meeting.opus',
sampleRate: 48_000,
numberOfChannels: 2,
},
},
]);
const { coordinator } = await createCoordinator();
const claimed = coordinator.claimImport(7, 'workspace-1');
expect(claimed).toMatchObject({
id: 7,
workspaceId: 'workspace-1',
docId: 'recording-7',
importStatus: 'importing',
});
expect(coordinator.importQueue()).toEqual([
expect.objectContaining({
id: 7,
workspaceId: 'workspace-1',
docId: 'recording-7',
importStatus: 'importing',
}),
]);
});
test('reopens interrupted imports as pending work while suppressing stale terminal popups', async () => {
storageState.set('recordingJobs:v2', [
{
id: 1,
phase: 'importing',
appName: 'Zoom',
startTime: 1000,
createdAt: 1,
updatedAt: 1,
artifact: {
filepath: '/tmp/interrupted.opus',
},
import: {
workspaceId: 'workspace-1',
docId: 'recording-1',
leaseExpiresAt: Date.now() + 10_000,
},
},
{
id: 2,
phase: 'imported',
appName: 'Meet',
startTime: 2000,
createdAt: 2,
updatedAt: 2,
artifact: {
filepath: '/tmp/imported.opus',
},
},
{
id: 3,
phase: 'failed',
appName: 'Teams',
startTime: 3000,
createdAt: 3,
updatedAt: 3,
artifact: {
filepath: '/tmp/failed.opus',
},
error: {
stage: 'import',
message: 'import failed',
},
},
]);
const { coordinator } = await createCoordinator();
expect(coordinator.importQueue()).toEqual([
expect.objectContaining({
id: 1,
importStatus: 'pending_import',
}),
]);
expect(coordinator.currentStatus()).toBeNull();
});
test('abortActive clears the local job even when native abort fails', async () => {
const startRecording = vi.fn().mockResolvedValue({
id: 'native-1',
filepath: '/tmp/0.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 123,
});
const abortRecording = vi
.fn()
.mockRejectedValue(new Error('native abort failed'));
const { coordinator } = await createCoordinator({
startRecording,
abortRecording,
});
await coordinator.start();
await expect(coordinator.abortActive()).rejects.toThrow(
'native abort failed'
);
expect(coordinator.currentStatus()).toBeNull();
expect(coordinator.jobs).toEqual([]);
});
test('start failures project to start_failed and release the active slot', async () => {
const startRecording = vi
.fn()
.mockRejectedValueOnce(new Error('native start failed'))
.mockResolvedValueOnce({
id: 'native-2',
filepath: '/tmp/1.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 456,
});
const { coordinator } = await createCoordinator({
startRecording,
});
const failed = await coordinator.start();
expect(failed).toMatchObject({
phase: 'failed',
error: {
stage: 'start',
message: 'native start failed',
},
});
expect(coordinator.currentStatus()).toMatchObject({
status: 'start_failed',
errorMessage: 'native start failed',
});
const next = await coordinator.start();
expect(next).toMatchObject({
id: 1,
phase: 'recording',
});
});
test('stop failures project to finalize_failed and release the active slot', async () => {
const startRecording = vi
.fn()
.mockResolvedValueOnce({
id: 'native-1',
filepath: '/tmp/0.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 123,
})
.mockResolvedValueOnce({
id: 'native-2',
filepath: '/tmp/1.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 456,
});
const stopRecording = vi
.fn()
.mockRejectedValueOnce(new Error('native stop failed'));
const { coordinator } = await createCoordinator({
startRecording,
stopRecording,
});
const first = await coordinator.start();
await coordinator.stop(first!.id);
expect(coordinator.currentStatus()).toMatchObject({
id: first!.id,
status: 'finalize_failed',
errorMessage: 'native stop failed',
});
const next = await coordinator.start();
expect(next).toMatchObject({
id: 1,
phase: 'recording',
});
});
test.each([
{
name: 'successful import completion',
settleImport: (coordinator: {
completeImport: (id: number) => unknown;
}) => coordinator.completeImport(7),
expectedStatus: 'imported',
},
{
name: 'failed import completion',
settleImport: (coordinator: {
failImport: (id: number, errorMessage?: string) => unknown;
}) => coordinator.failImport(7, 'import failed'),
expectedStatus: 'import_failed',
},
])(
'projects $name without leaking completed queue items into the import queue',
async ({ settleImport, expectedStatus }) => {
storageState.set('recordingJobs:v2', [
{
id: 7,
phase: 'recorded',
appName: 'Zoom',
startTime: 1000,
createdAt: 1,
updatedAt: 1,
artifact: {
filepath: '/tmp/meeting.opus',
sampleRate: 48_000,
numberOfChannels: 2,
},
},
]);
const { coordinator } = await createCoordinator();
settleImport(coordinator as never);
expect(coordinator.currentStatus()).toMatchObject({
id: 7,
status: expectedStatus,
});
expect(coordinator.importQueue()).toEqual([]);
}
);
test.each([
{
name: 'successful imports',
seed: {
id: 11,
phase: 'imported' as const,
appName: 'Zoom',
startTime: 1000,
createdAt: 1,
updatedAt: 1,
artifact: {
filepath: '/tmp/imported.opus',
},
},
},
{
name: 'failed imports',
seed: {
id: 12,
phase: 'failed' as const,
appName: 'Meet',
startTime: 1000,
createdAt: 1,
updatedAt: 1,
artifact: {
filepath: '/tmp/failed.opus',
},
error: {
stage: 'import' as const,
message: 'import failed',
},
},
},
])(
'suppresses persisted terminal $name from the current status',
async ({ seed }) => {
storageState.set('recordingJobs:v2', [seed]);
const { coordinator } = await createCoordinator();
expect(coordinator.currentStatus()).toBeNull();
expect(coordinator.importQueue()).toEqual([]);
}
);
test('dismissing an import failure clears the popup projection without dropping the saved artifact', async () => {
storageState.set('recordingJobs:v2', [
{
id: 7,
phase: 'failed',
appName: 'Zoom',
startTime: 1000,
createdAt: 1,
updatedAt: 1,
artifact: {
filepath: '/tmp/meeting.opus',
},
error: {
stage: 'import',
message: 'import failed',
},
},
]);
const { coordinator } = await createCoordinator();
coordinator.dismiss(7);
expect(coordinator.currentStatus()).toBeNull();
expect(coordinator.importQueue()).toEqual([]);
expect(storageState.get('recordingJobs:v2')).toEqual([
expect.objectContaining({
id: 7,
phase: 'failed',
dismissedAt: expect.any(Number),
artifact: expect.objectContaining({
filepath: '/tmp/meeting.opus',
}),
error: {
stage: 'import',
message: 'import failed',
},
}),
]);
});
});

View File

@@ -0,0 +1,628 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
const isActiveTab = vi.fn();
const readRecordingFile = vi.fn();
const claimRecordingImport = vi.fn();
const completeRecordingImport = vi.fn();
const failRecordingImport = vi.fn();
const getRecordingImportQueue = vi.fn();
const getCurrentWorkspace = vi.fn();
const isAiEnabled = vi.fn();
const transcribeRecording = vi.fn();
type RecordingImportStatus = {
id: number;
appName?: string;
workspaceId?: string;
docId?: string;
filepath: string;
startTime: number;
sampleRate?: number;
numberOfChannels?: number;
durationMs?: number;
size?: number;
degraded?: boolean;
overflowCount?: number;
errorMessage?: string;
importStatus: 'pending_import' | 'importing' | 'imported' | 'import_failed';
createdAt: number;
updatedAt: number;
};
function withQueueMeta(
status: Omit<RecordingImportStatus, 'createdAt' | 'updatedAt'>
): RecordingImportStatus {
return {
createdAt: 1,
updatedAt: 1,
...status,
};
}
let onRecordingImportQueueChanged:
| ((queue: RecordingImportStatus[]) => void)
| undefined;
vi.mock('@affine/core/modules/doc', () => ({
DocsService: class DocsService {},
}));
vi.mock('@affine/core/modules/media/services/audio-attachment', () => ({
AudioAttachmentService: class AudioAttachmentService {},
}));
vi.mock('@affine/core/modules/workbench', () => ({
WorkbenchService: class WorkbenchService {},
}));
vi.mock('@affine/debug', () => ({
DebugLogger: class DebugLogger {
debug = vi.fn();
error = vi.fn();
},
}));
vi.mock('@affine/electron-api', () => ({
apis: {
ui: {
isActiveTab,
},
recording: {
readRecordingFile,
claimRecordingImport,
completeRecordingImport,
failRecordingImport,
getRecordingImportQueue,
},
},
events: {
recording: {
onRecordingImportQueueChanged: vi.fn(
(handler: typeof onRecordingImportQueueChanged) => {
onRecordingImportQueueChanged = handler;
return () => {
onRecordingImportQueueChanged = undefined;
};
}
),
},
},
}));
vi.mock('@affine/i18n', () => ({
i18nTime: vi.fn(() => 'Jan 1 09:00'),
}));
vi.mock('@affine/track', () => ({
default: {
doc: {
editor: {
audioBlock: {
transcribeRecording,
},
},
},
},
}));
vi.mock('../../../electron-renderer/src/app/effects/utils', () => ({
getCurrentWorkspace,
isAiEnabled,
}));
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function createWorkspaceRef() {
const blobSet = vi.fn(async () => 'blob-1');
const openDoc = vi.fn();
const createdDocs = new Set<string>();
type MockBlockRecord = { model: unknown } | null;
type MockBlockStore = {
addBlock: (
flavour: string,
props: Record<string, unknown>,
parentId?: string
) => string;
getBlock: (id: string) => MockBlockRecord;
getBlock$: (id: string) => MockBlockRecord;
};
const attachments: Array<{
id: string;
props: { name: string; type: string };
childMap: { value: Map<string, true> };
store: MockBlockStore;
}> = [];
const transcriptionBlocks: Array<{
id: string;
flavour: string;
props: {
transcription: {
sourceAudio?: Record<string, unknown>;
quality?: Record<string, unknown>;
};
};
}> = [];
const blockSuiteDoc = {
getModelsByFlavour: vi.fn((flavour: string) => {
if (flavour === 'affine:page') {
return [{ id: 'page-1' }];
}
if (flavour === 'affine:note') {
return [{ id: 'note-1' }];
}
if (flavour === 'affine:attachment') {
return attachments;
}
return [];
}),
addBlock: vi.fn(
(flavour: string, props: Record<string, unknown>, parentId?: string) => {
if (flavour === 'affine:attachment') {
const id = `attachment-${attachments.length + 1}`;
const attachment = {
id,
props: {
name: typeof props.name === 'string' ? props.name : '',
type: typeof props.type === 'string' ? props.type : '',
},
childMap: { value: new Map<string, true>() },
store: {
addBlock: (...args: Parameters<typeof blockSuiteDoc.addBlock>) =>
blockSuiteDoc.addBlock(...args),
getBlock: (blockId: string) => blockSuiteDoc.getBlock(blockId),
getBlock$: (blockId: string) => blockSuiteDoc.getBlock(blockId),
},
};
attachments.push(attachment);
return id;
}
if (flavour === 'affine:transcription') {
const id = `transcription-${transcriptionBlocks.length + 1}`;
const block = {
id,
flavour,
props: {
transcription:
(props.transcription as {
sourceAudio?: Record<string, unknown>;
quality?: Record<string, unknown>;
}) ?? {},
},
};
transcriptionBlocks.push(block);
const attachment = attachments.find(entry => entry.id === parentId);
attachment?.childMap.value.set(id, true);
return id;
}
return `${flavour}-1`;
}
),
getBlock: vi.fn((id: string) => {
const attachment = attachments.find(entry => entry.id === id);
if (attachment) {
return { model: attachment };
}
const transcriptionBlock = transcriptionBlocks.find(
entry => entry.id === id
);
return transcriptionBlock ? { model: transcriptionBlock } : null;
}),
};
const createDoc = vi.fn(({ id }: { id: string }) => {
createdDocs.add(id);
return { id };
});
const open = vi.fn((docId: string) => {
if (!createdDocs.has(docId)) {
throw new Error(`Doc ${docId} not found`);
}
return {
doc: {
workspace: { id: 'workspace-1' },
blockSuiteDoc,
addPriorityLoad: vi.fn(() => vi.fn()),
waitForSyncReady: vi.fn(async () => undefined),
},
release: vi.fn(),
};
});
const scope = {
get(token: { name?: string }) {
switch (token.name) {
case 'DocsService':
return {
createDoc,
open,
list: {
['doc$']: (docId: string) => ({
value: createdDocs.has(docId) ? { id: docId } : null,
}),
},
};
case 'WorkbenchService':
return { workbench: { openDoc } };
case 'AudioAttachmentService':
return {
get: () => ({
obj: {
transcribe: vi.fn(async () => undefined),
},
[Symbol.dispose]: vi.fn(),
}),
};
default:
throw new Error(`Unexpected token: ${token.name}`);
}
},
};
const dispose = vi.fn();
return {
ref: {
workspace: {
id: 'workspace-1',
scope,
docCollection: {
blobSync: { set: blobSet },
},
},
dispose,
[Symbol.dispose]: dispose,
},
createDoc,
openDoc,
blobSet,
attachments,
transcriptionBlocks,
};
}
describe('recording effect', () => {
beforeEach(() => {
vi.useFakeTimers();
vi.clearAllMocks();
vi.resetModules();
onRecordingImportQueueChanged = undefined;
readRecordingFile.mockResolvedValue(new Uint8Array([1, 2, 3]).buffer);
completeRecordingImport.mockResolvedValue(undefined);
failRecordingImport.mockResolvedValue(undefined);
isAiEnabled.mockReturnValue(false);
getRecordingImportQueue.mockResolvedValue([]);
});
afterEach(() => {
vi.runOnlyPendingTimers();
vi.useRealTimers();
});
test('retries pending imports until the active tab has a workspace and claims with workspace binding', async () => {
const workspace = createWorkspaceRef();
const pendingImport = {
id: 7,
importStatus: 'pending_import' as const,
appName: 'Zoom',
filepath: '/tmp/meeting.opus',
startTime: 1000,
};
isActiveTab.mockResolvedValueOnce(false).mockResolvedValue(true);
getCurrentWorkspace
.mockReturnValueOnce(undefined)
.mockReturnValue(workspace.ref);
claimRecordingImport.mockResolvedValue({
...withQueueMeta(pendingImport),
workspaceId: 'workspace-1',
docId: 'recording-7',
importStatus: 'importing',
});
getRecordingImportQueue.mockResolvedValue([withQueueMeta(pendingImport)]);
const { setupRecordingEvents } =
await import('../../../electron-renderer/src/app/effects/recording');
setupRecordingEvents({} as never);
await Promise.resolve();
expect(workspace.createDoc).not.toHaveBeenCalled();
expect(claimRecordingImport).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1000);
expect(workspace.createDoc).not.toHaveBeenCalled();
expect(claimRecordingImport).not.toHaveBeenCalled();
onRecordingImportQueueChanged?.([withQueueMeta(pendingImport)]);
await vi.advanceTimersByTimeAsync(1000);
expect(claimRecordingImport).toHaveBeenCalledWith(7, 'workspace-1');
expect(workspace.createDoc).toHaveBeenCalledWith(
expect.objectContaining({ id: 'recording-7' })
);
expect(workspace.openDoc).toHaveBeenCalledWith('recording-7');
expect(workspace.blobSet).toHaveBeenCalledTimes(1);
expect(completeRecordingImport).toHaveBeenCalledWith(7);
expect(failRecordingImport).not.toHaveBeenCalled();
});
test('reuses the same doc when a claimed import already carries docId', async () => {
const workspace = createWorkspaceRef();
const pendingImport = {
id: 8,
importStatus: 'pending_import' as const,
appName: 'Meet',
filepath: '/tmp/meeting.opus',
startTime: 1000,
workspaceId: 'workspace-1',
docId: 'recording-8',
};
workspace.createDoc({ id: 'recording-8' });
isActiveTab.mockResolvedValue(true);
getCurrentWorkspace.mockReturnValue(workspace.ref);
claimRecordingImport.mockResolvedValue({
...withQueueMeta(pendingImport),
importStatus: 'importing',
});
getRecordingImportQueue.mockResolvedValue([withQueueMeta(pendingImport)]);
const { setupRecordingEvents } =
await import('../../../electron-renderer/src/app/effects/recording');
setupRecordingEvents({} as never);
await Promise.resolve();
await Promise.resolve();
await vi.advanceTimersByTimeAsync(0);
expect(workspace.createDoc).toHaveBeenCalledTimes(1);
expect(workspace.blobSet).toHaveBeenCalledTimes(1);
expect(completeRecordingImport).toHaveBeenCalledWith(8);
});
test('writes recording metadata into the transcription block', async () => {
const workspace = createWorkspaceRef();
const pendingImport = withQueueMeta({
id: 18,
importStatus: 'pending_import',
appName: 'Meet',
filepath: '/tmp/meeting.opus',
startTime: 1000,
sampleRate: 48_000,
numberOfChannels: 2,
durationMs: 120_000,
degraded: true,
overflowCount: 4,
});
isActiveTab.mockResolvedValue(true);
getCurrentWorkspace.mockReturnValue(workspace.ref);
claimRecordingImport.mockResolvedValue({
...pendingImport,
workspaceId: 'workspace-1',
docId: 'recording-18',
importStatus: 'importing',
});
getRecordingImportQueue.mockResolvedValue([pendingImport]);
const { setupRecordingEvents } =
await import('../../../electron-renderer/src/app/effects/recording');
setupRecordingEvents({} as never);
await Promise.resolve();
await Promise.resolve();
await vi.advanceTimersByTimeAsync(0);
expect(workspace.transcriptionBlocks).toHaveLength(1);
expect(workspace.transcriptionBlocks[0]?.props.transcription).toEqual({
sourceAudio: {
mimeType: 'audio/ogg',
durationMs: 120_000,
sampleRate: 48_000,
channels: 2,
},
quality: {
degraded: true,
overflowCount: 4,
},
});
});
test('marks imports as failed when blob import fails after claim', async () => {
const pendingImport = {
id: 9,
importStatus: 'pending_import' as const,
appName: 'Meet',
filepath: '/tmp/meeting.opus',
startTime: 1000,
};
const workspace = createWorkspaceRef();
workspace.blobSet.mockRejectedValueOnce(new Error('blob import failed'));
isActiveTab.mockResolvedValue(true);
getCurrentWorkspace.mockReturnValue(workspace.ref);
claimRecordingImport.mockResolvedValue({
...withQueueMeta(pendingImport),
workspaceId: 'workspace-1',
docId: 'recording-9',
importStatus: 'importing',
});
getRecordingImportQueue.mockResolvedValue([withQueueMeta(pendingImport)]);
const { setupRecordingEvents } =
await import('../../../electron-renderer/src/app/effects/recording');
setupRecordingEvents({} as never);
await Promise.resolve();
await Promise.resolve();
await vi.advanceTimersByTimeAsync(0);
expect(failRecordingImport).toHaveBeenCalledWith(9, 'blob import failed');
expect(completeRecordingImport).not.toHaveBeenCalled();
});
test('releases priority load when waiting for sync readiness fails', async () => {
const pendingImport = {
id: 10,
importStatus: 'pending_import' as const,
appName: 'Meet',
filepath: '/tmp/meeting.opus',
startTime: 1000,
};
const disposePriorityLoad = vi.fn();
const release = vi.fn();
const workspace = {
ref: {
workspace: {
id: 'workspace-1',
scope: {
get(token: { name?: string }) {
switch (token.name) {
case 'DocsService':
return {
createDoc: vi.fn(),
open: vi.fn(() => ({
doc: {
blockSuiteDoc: {},
addPriorityLoad: vi.fn(() => disposePriorityLoad),
waitForSyncReady: vi
.fn()
.mockRejectedValue(new Error('sync failed')),
},
release,
})),
list: {
['doc$']: vi.fn(() => ({
value: { id: 'recording-10' },
})),
},
};
case 'WorkbenchService':
case 'AudioAttachmentService':
return {};
default:
throw new Error(`Unexpected token: ${token.name}`);
}
},
},
docCollection: {
blobSync: { set: vi.fn() },
},
},
dispose: vi.fn(),
[Symbol.dispose]: vi.fn(),
},
};
isActiveTab.mockResolvedValue(true);
getCurrentWorkspace.mockReturnValue(workspace.ref);
claimRecordingImport.mockResolvedValue({
...withQueueMeta(pendingImport),
workspaceId: 'workspace-1',
docId: 'recording-10',
importStatus: 'importing',
});
getRecordingImportQueue.mockResolvedValue([withQueueMeta(pendingImport)]);
const { setupRecordingEvents } =
await import('../../../electron-renderer/src/app/effects/recording');
setupRecordingEvents({} as never);
await Promise.resolve();
await Promise.resolve();
await vi.advanceTimersByTimeAsync(0);
expect(disposePriorityLoad).toHaveBeenCalledTimes(1);
expect(release).toHaveBeenCalledTimes(1);
expect(failRecordingImport).toHaveBeenCalledWith(10, 'sync failed');
expect(completeRecordingImport).not.toHaveBeenCalled();
});
test('processes recording imports one at a time even when the queue changes mid-import', async () => {
const firstImport = {
id: 7,
importStatus: 'pending_import' as const,
appName: 'Zoom',
filepath: '/tmp/meeting-1.opus',
startTime: 1000,
};
const secondImport = {
id: 8,
importStatus: 'pending_import' as const,
appName: 'Meet',
filepath: '/tmp/meeting-2.opus',
startTime: 2000,
};
const firstRead = createDeferred<ArrayBuffer>();
const workspace = createWorkspaceRef();
isActiveTab.mockResolvedValue(true);
getCurrentWorkspace.mockReturnValue(workspace.ref);
readRecordingFile
.mockImplementationOnce(() => firstRead.promise)
.mockResolvedValueOnce(new Uint8Array([4, 5, 6]).buffer);
claimRecordingImport.mockImplementation(async (id: number) => ({
...(id === firstImport.id ? firstImport : secondImport),
workspaceId: 'workspace-1',
docId: `recording-${id}`,
importStatus: 'importing' as const,
createdAt: 1,
updatedAt: 1,
}));
getRecordingImportQueue.mockResolvedValue([
withQueueMeta(firstImport),
withQueueMeta(secondImport),
]);
const { setupRecordingEvents } =
await import('../../../electron-renderer/src/app/effects/recording');
setupRecordingEvents({} as never);
await Promise.resolve();
await Promise.resolve();
await vi.advanceTimersByTimeAsync(0);
expect(claimRecordingImport).toHaveBeenCalledTimes(1);
expect(claimRecordingImport).toHaveBeenCalledWith(
firstImport.id,
'workspace-1'
);
onRecordingImportQueueChanged?.([
withQueueMeta({
...firstImport,
workspaceId: 'workspace-1',
docId: 'recording-7',
importStatus: 'importing',
}),
withQueueMeta(secondImport),
]);
await Promise.resolve();
expect(claimRecordingImport).toHaveBeenCalledTimes(1);
firstRead.resolve(new Uint8Array([1, 2, 3]).buffer);
await Promise.resolve();
await Promise.resolve();
await vi.advanceTimersByTimeAsync(1000);
expect(claimRecordingImport).toHaveBeenCalledTimes(2);
expect(claimRecordingImport).toHaveBeenNthCalledWith(
2,
secondImport.id,
'workspace-1'
);
expect(completeRecordingImport).toHaveBeenNthCalledWith(1, firstImport.id);
expect(completeRecordingImport).toHaveBeenNthCalledWith(2, secondImport.id);
});
});

View File

@@ -0,0 +1,340 @@
import { BehaviorSubject } from 'rxjs';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
const nativeStartRecording = vi.fn();
const nativeStopRecording = vi.fn();
const nativeAbortRecording = vi.fn();
const ensureDirSync = vi.fn();
const resolveExistingPathInBase = vi.fn(
async (_base: string, filepath: string) => filepath
);
const showMainWindow = vi.fn(async () => undefined);
const storageState = new Map<string, unknown>();
const watchSubjects = new Map<string, BehaviorSubject<unknown>>();
function createDeferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
storageState.clear();
watchSubjects.clear();
vi.doMock('@affine/native', () => ({
ShareableContent: class ShareableContent {
static applications() {
return [];
}
static applicationWithProcessId() {
return null;
}
static isUsingMicrophone() {
return false;
}
static onApplicationListChanged() {
return { unsubscribe: vi.fn() };
}
static onAppStateChanged() {
return { unsubscribe: vi.fn() };
}
},
startRecording: nativeStartRecording,
stopRecording: nativeStopRecording,
abortRecording: nativeAbortRecording,
}));
vi.doMock('electron', () => ({
app: {
getPath: vi.fn(() => '/tmp'),
on: vi.fn(),
},
systemPreferences: {
getMediaAccessStatus: vi.fn(() => 'granted'),
askForMediaAccess: vi.fn(async () => true),
},
}));
vi.doMock('fs-extra', () => ({
default: {
ensureDirSync,
removeSync: vi.fn(),
},
}));
vi.doMock('../../src/shared/utils', async () => {
const actual = await vi.importActual('../../src/shared/utils');
return {
...actual,
isMacOS: () => false,
isWindows: () => false,
resolveExistingPathInBase,
};
});
vi.doMock('../../src/main/shared-storage/storage', () => ({
globalStateStorage: {
get: (key: string) => storageState.get(key),
set: (key: string, value: unknown) => {
storageState.set(key, value);
watchSubjects.get(key)?.next(value);
},
watch: (key: string) => {
const watchSubject$ =
watchSubjects.get(key) ?? new BehaviorSubject(storageState.get(key));
watchSubjects.set(key, watchSubject$);
return watchSubject$.asObservable();
},
},
}));
vi.doMock('../../src/main/windows-manager', () => ({
showMainWindow,
}));
vi.doMock('../../src/main/windows-manager/popup', () => ({
popupManager: {
get: () => ({
showing: false,
show: vi.fn(async () => undefined),
hide: vi.fn(async () => undefined),
}),
},
}));
vi.doMock('lodash-es', () => ({
debounce: (fn: (...args: unknown[]) => void) => fn,
}));
});
async function loadRecordingFeature() {
const feature = await import('../../src/main/recording/feature');
feature.setRecordingNativeModuleForTesting({
ShareableContent: class ShareableContent {
static applications() {
return [];
}
static applicationWithProcessId() {
return null;
}
static isUsingMicrophone() {
return false;
}
static onApplicationListChanged() {
return { unsubscribe: vi.fn() };
}
static onAppStateChanged() {
return { unsubscribe: vi.fn() };
}
},
startRecording: nativeStartRecording,
stopRecording: nativeStopRecording,
abortRecording: nativeAbortRecording,
} as never);
return feature;
}
afterEach(() => {
vi.clearAllTimers();
});
describe('recording feature', () => {
test('slow start exposes starting state before native setup resolves', async () => {
const startDeferred = createDeferred<{
id: string;
filepath: string;
sampleRate: number;
channels: number;
startedAt: number;
}>();
nativeStartRecording.mockReturnValue(startDeferred.promise);
const { getCurrentRecordingStatus, startRecording } =
await loadRecordingFeature();
const startPromise = startRecording();
expect(getCurrentRecordingStatus()).toMatchObject({
status: 'starting',
});
startDeferred.resolve({
id: 'native-1',
filepath: '/tmp/0.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 123,
});
await startPromise;
expect(getCurrentRecordingStatus()).toMatchObject({
status: 'recording',
});
expect(getCurrentRecordingStatus()?.filepath).toContain('0.opus');
});
test('stop handoff moves from finalizing to pending_import without clearing the popup state', async () => {
nativeStartRecording.mockResolvedValue({
id: 'native-1',
filepath: '/tmp/0.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 123,
});
const stopDeferred = createDeferred<{
id: string;
filepath: string;
sampleRate: number;
channels: number;
durationMs: number;
size: number;
degraded: boolean;
overflowCount: number;
}>();
nativeStopRecording.mockReturnValue(stopDeferred.promise);
const {
getCurrentRecordingStatus,
getRecordingImportQueue,
recordingStatus$,
startRecording,
stopRecording,
} = await loadRecordingFeature();
const started = await startRecording();
const seenStatuses: Array<string | null> = [];
const subscription = recordingStatus$.subscribe(status => {
seenStatuses.push(status?.status ?? null);
});
const stopPromise = stopRecording(started!.id);
expect(getCurrentRecordingStatus()).toMatchObject({
id: started!.id,
status: 'finalizing',
});
stopDeferred.resolve({
id: 'native-1',
filepath: '/tmp/0.opus',
sampleRate: 48_000,
channels: 2,
durationMs: 2_000,
size: 256,
degraded: true,
overflowCount: 4,
});
await stopPromise;
subscription.unsubscribe();
expect(showMainWindow).toHaveBeenCalledOnce();
expect(getCurrentRecordingStatus()).toMatchObject({
id: started!.id,
status: 'pending_import',
degraded: true,
overflowCount: 4,
});
expect(getRecordingImportQueue()).toEqual([
expect.objectContaining({
id: started!.id,
importStatus: 'pending_import',
filepath: '/tmp/0.opus',
degraded: true,
overflowCount: 4,
}),
]);
expect(seenStatuses).toContain('finalizing');
expect(seenStatuses).toContain('pending_import');
expect(seenStatuses).not.toContain(null);
});
test('system-audio start does not reuse a pending app-scoped prompt', async () => {
nativeStartRecording.mockResolvedValue({
id: 'native-1',
filepath: '/tmp/system.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 123,
});
const { newRecording, startRecording } = await loadRecordingFeature();
newRecording({
processGroupId: 100,
name: 'Zoom',
bundleIdentifier: 'us.zoom.xos',
icon: undefined,
isRunning: true,
apps: [
{
info: {} as never,
isRunning: true,
processId: 42,
processGroupId: 100,
bundleIdentifier: 'us.zoom.xos',
name: 'Zoom',
},
],
});
await startRecording();
expect(nativeStartRecording).toHaveBeenCalledWith(
expect.objectContaining({
appProcessId: undefined,
})
);
});
test('disableRecordingFeature clears the active session so a new recording can start', async () => {
nativeStartRecording
.mockResolvedValueOnce({
id: 'native-1',
filepath: '/tmp/0.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 123,
})
.mockResolvedValueOnce({
id: 'native-2',
filepath: '/tmp/1.opus',
sampleRate: 48_000,
channels: 2,
startedAt: 456,
});
const feature = await loadRecordingFeature();
const first = await feature.startRecording();
expect(feature.getCurrentRecordingStatus()).toMatchObject({
id: first!.id,
status: 'recording',
});
await feature.disableRecordingFeature();
expect(feature.getCurrentRecordingStatus()).toBeNull();
expect(nativeAbortRecording).toHaveBeenCalledWith('native-1');
const second = await feature.startRecording();
expect(second).toMatchObject({
id: expect.any(Number),
status: 'recording',
});
expect(second!.id).toBeGreaterThan(first!.id);
});
});

View File

@@ -0,0 +1,75 @@
import { BehaviorSubject } from 'rxjs';
import { describe, expect, test, vi } from 'vitest';
const recordingStatus$ = new BehaviorSubject(null);
const recordingImportQueue$ = new BehaviorSubject([
{
id: 7,
appName: 'Zoom',
workspaceId: 'workspace-1',
docId: 'recording-7',
startTime: 1000,
filepath: '/tmp/meeting.opus',
importStatus: 'importing' as const,
createdAt: 1,
updatedAt: 1,
},
]);
vi.mock('electron', () => ({
shell: {
showItemInFolder: vi.fn(),
},
}));
vi.mock('../../src/shared/utils', () => ({
isMacOS: () => false,
resolvePathInBase: vi.fn((_base: string, subpath: string) => subpath),
}));
vi.mock('../../src/main/security/open-external', () => ({
openExternalSafely: vi.fn(),
}));
vi.mock('../../src/main/recording/feature', () => ({
askForMeetingPermission: vi.fn(),
checkMeetingPermissions: vi.fn(),
checkRecordingAvailable: vi.fn(),
claimRecordingImport: vi.fn(),
completeRecordingImport: vi.fn(),
disableRecordingFeature: vi.fn(),
dismissRecordingStatus: vi.fn(),
failRecordingImport: vi.fn(),
getCurrentRecordingStatus: vi.fn(),
getRecording: vi.fn(),
getRecordingImportQueue: vi.fn(),
readRecordingFile: vi.fn(),
recordingImportQueue$,
recordingStatus$,
removeRecording: vi.fn(),
SAVED_RECORDINGS_DIR: '/tmp',
serializeRecordingStatus: vi.fn(),
setupRecordingFeature: vi.fn(),
startRecording: vi.fn(),
stopRecording: vi.fn(),
}));
describe('recording index events', () => {
test('onRecordingImportQueueChanged preserves workspace binding metadata', async () => {
const { recordingEvents } = await import('../../src/main/recording');
const handler = vi.fn();
const unsubscribe = recordingEvents.onRecordingImportQueueChanged(handler);
expect(handler).toHaveBeenCalledWith([
expect.objectContaining({
id: 7,
workspaceId: 'workspace-1',
docId: 'recording-7',
importStatus: 'importing',
}),
]);
unsubscribe();
});
});

View File

@@ -0,0 +1,109 @@
import { describe, expect, it, vi } from 'vitest';
describe('redirect proxy allowlist', () => {
it('blocks missing redirect_uri', async () => {
vi.resetModules();
process.env.BUILD_TYPE = 'stable';
process.env.NODE_ENV = 'production';
delete process.env.DEV_SERVER_URL;
const { validateRedirectProxyUrl } =
await import('../../src/main/security/redirect-proxy');
expect(validateRedirectProxyUrl('assets://./redirect-proxy')).toEqual({
allow: false,
reason: 'missing_redirect_target',
});
});
it('blocks untrusted redirect_uri', async () => {
vi.resetModules();
process.env.BUILD_TYPE = 'stable';
process.env.NODE_ENV = 'production';
delete process.env.DEV_SERVER_URL;
const { validateRedirectProxyUrl } =
await import('../../src/main/security/redirect-proxy');
expect(
validateRedirectProxyUrl(
'assets://./redirect-proxy?redirect_uri=https%3A%2F%2Fevil.com%2F'
)
).toEqual({
allow: false,
reason: 'untrusted_redirect_target',
redirectTarget: 'https://evil.com/',
});
});
it('allows trusted redirect_uri', async () => {
vi.resetModules();
process.env.BUILD_TYPE = 'stable';
process.env.NODE_ENV = 'production';
delete process.env.DEV_SERVER_URL;
const { validateRedirectProxyUrl } =
await import('../../src/main/security/redirect-proxy');
expect(
validateRedirectProxyUrl(
'assets://./redirect-proxy?redirect_uri=https%3A%2F%2Fgithub.com%2Ftoeverything%2FAFFiNE'
)
).toEqual({
allow: true,
redirectTarget: 'https://github.com/toeverything/AFFiNE',
});
});
it('allows current hostname (canary)', async () => {
vi.resetModules();
process.env.BUILD_TYPE = 'canary';
process.env.NODE_ENV = 'production';
delete process.env.DEV_SERVER_URL;
const { validateRedirectProxyUrl } =
await import('../../src/main/security/redirect-proxy');
expect(
validateRedirectProxyUrl(
'assets://./redirect-proxy?redirect_uri=https%3A%2F%2Faffine.fail%2Fpricing'
)
).toEqual({
allow: true,
redirectTarget: 'https://affine.fail/pricing',
});
});
it('allows current hostname from DEV_SERVER_URL in development', async () => {
vi.resetModules();
process.env.BUILD_TYPE = 'stable';
process.env.NODE_ENV = 'development';
process.env.DEV_SERVER_URL = 'http://localhost:8080';
const { validateRedirectProxyUrl } =
await import('../../src/main/security/redirect-proxy');
expect(
validateRedirectProxyUrl(
'assets://./redirect-proxy?redirect_uri=http%3A%2F%2Flocalhost%3A1234%2Fauth'
)
).toEqual({
allow: true,
redirectTarget: 'http://localhost:1234/auth',
});
});
it('blocks redirect_uri in hash when untrusted', async () => {
vi.resetModules();
process.env.BUILD_TYPE = 'stable';
process.env.NODE_ENV = 'production';
delete process.env.DEV_SERVER_URL;
const { validateRedirectProxyUrl } =
await import('../../src/main/security/redirect-proxy');
expect(
validateRedirectProxyUrl(
'assets://./redirect-proxy#/foo?redirect_uri=https%3A%2F%2Fevil.com%2F'
)
).toEqual({
allow: false,
reason: 'untrusted_redirect_target',
redirectTarget: 'https://evil.com/',
});
});
});

View File

@@ -0,0 +1,146 @@
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { UpdateCheckResult } from 'electron-updater';
import { parseUpdateInfo } from 'electron-updater/out/providers/Provider';
import fs from 'fs-extra';
import { flatten } from 'lodash-es';
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';
import {
afterAll,
afterEach,
beforeAll,
describe,
expect,
it,
vi,
} from 'vitest';
import {
AFFiNEUpdateProvider,
availableForMyPlatformAndInstaller,
} from '../../src/main/updater/affine-update-provider';
import { MockedAppAdapter, MockedUpdater } from './mocks';
const __dirname = fileURLToPath(new URL('.', import.meta.url));
vi.mock('electron', () => ({
app: {
getPath: () => __dirname,
},
}));
describe('testing for client update', () => {
const expectReleaseList = [
{ buildType: 'beta', version: '0.16.3-beta.2' },
{ buildType: 'canary', version: '0.17.0-canary.7' },
{ buildType: 'stable', version: '0.18.0' },
];
const basicRequestHandlers = [
http.get('https://affine.pro/api/worker/releases', async ({ request }) => {
const url = new URL(request.url);
const buffer = await fs.readFile(
path.join(
__dirname,
'fixtures',
'candidates',
`${url.searchParams.get('channel')}.json`
)
);
const content = buffer.toString();
return HttpResponse.text(content);
}),
...flatten(
expectReleaseList.map(({ version }) => {
return [
http.get(
`https://github.com/toeverything/AFFiNE/releases/download/v${version}/latest.yml`,
async req => {
const buffer = await fs.readFile(
path.join(
__dirname,
'fixtures',
'releases',
version,
path.parse(req.request.url).base
)
);
const content = buffer.toString();
return HttpResponse.text(content);
}
),
];
})
),
];
describe('release api request successfully', () => {
const server = setupServer(...basicRequestHandlers);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterAll(() => server.close());
afterEach(() => server.resetHandlers());
for (const { buildType, version } of expectReleaseList) {
it(`check update for ${buildType} channel successfully`, async () => {
const app = new MockedAppAdapter('0.10.0');
const updater = new MockedUpdater(null, app);
updater.setFeedURL(
AFFiNEUpdateProvider.configFeed({
channel: buildType as any,
})
);
const info = (await updater.checkForUpdates()) as UpdateCheckResult;
expect(info).not.toBe(null);
expect(info.updateInfo.releaseName).toBe(version);
expect(info.updateInfo.version).toBe(version);
// expect(info.updateInfo.releaseNotes?.length).toBeGreaterThan(0);
});
}
});
describe('filter valid installer files', async () => {
const platforms: NodeJS.Platform[] = ['darwin', 'win32', 'linux'];
const arches: NodeJS.Architecture[] = ['x64', 'arm64'];
for (const platform of platforms) {
for (const arch of arches) {
if (platform === 'linux' && arch === 'arm64') {
// not support arm64 on linux yet
continue;
}
const data = await fs.readFile(
path.join(__dirname, 'fixtures', 'releases', '0.18.0', `latest.yml`),
'utf-8'
);
const files = parseUpdateInfo(
data,
'',
new URL('https://affine.pro')
).files.map(file => file.url);
it(`filter for platform [${platform}] arch [${arch}]`, () => {
expect(
files.filter(file =>
availableForMyPlatformAndInstaller(file, platform, arch, false)
)
).toMatchSnapshot();
});
if (platform === 'win32') {
it(`filter for platform [${platform}] arch [${arch}] and is squirrel installer`, () => {
expect(
files.filter(file =>
availableForMyPlatformAndInstaller(file, platform, arch, true)
)
).toMatchSnapshot();
});
}
}
}
});
});

View File

@@ -0,0 +1,177 @@
import path from 'node:path';
import { universalId } from '@affine/nbstore';
import fs from 'fs-extra';
import { v4 } from 'uuid';
import { afterAll, afterEach, describe, expect, test, vi } from 'vitest';
const tmpDir = path.join(__dirname, 'tmp');
const appDataPath = path.join(tmpDir, 'app-data');
vi.doMock('@affine/electron/helper/db/ensure-db', () => ({
ensureSQLiteDB: async () => ({
destroy: () => {},
}),
}));
vi.doMock('@affine/electron/helper/main-rpc', () => ({
mainRPC: {
getPath: async () => appDataPath,
},
}));
afterEach(async () => {
try {
await fs.remove(tmpDir);
} catch (e) {
console.error(e);
}
});
afterAll(() => {
vi.doUnmock('@affine/electron/helper/main-rpc');
});
describe('workspace db management', () => {
test('list local workspace ids', async () => {
const { listLocalWorkspaceIds } =
await import('@affine/electron/helper/workspace/handlers');
const validWorkspaceId = v4();
const noDbWorkspaceId = v4();
const deletedWorkspaceId = v4();
const fileEntry = 'README.txt';
const validWorkspacePath = path.join(
appDataPath,
'workspaces',
'local',
validWorkspaceId
);
const noDbWorkspacePath = path.join(
appDataPath,
'workspaces',
'local',
noDbWorkspaceId
);
const deletedWorkspacePath = path.join(
appDataPath,
'workspaces',
'local',
deletedWorkspaceId
);
const deletedWorkspaceTrashPath = path.join(
appDataPath,
'deleted-workspaces',
deletedWorkspaceId
);
const nonDirectoryPath = path.join(
appDataPath,
'workspaces',
'local',
fileEntry
);
await fs.ensureDir(validWorkspacePath);
await fs.ensureFile(path.join(validWorkspacePath, 'storage.db'));
await fs.ensureDir(noDbWorkspacePath);
await fs.ensureDir(deletedWorkspacePath);
await fs.ensureFile(path.join(deletedWorkspacePath, 'storage.db'));
await fs.ensureDir(deletedWorkspaceTrashPath);
await fs.outputFile(nonDirectoryPath, 'not-a-workspace');
const ids = await listLocalWorkspaceIds();
expect(ids).toContain(validWorkspaceId);
expect(ids).not.toContain(noDbWorkspaceId);
expect(ids).not.toContain(deletedWorkspaceId);
expect(ids).not.toContain(fileEntry);
});
test('trash workspace', async () => {
const { trashWorkspace } =
await import('@affine/electron/helper/workspace/handlers');
const workspaceId = v4();
const workspacePath = path.join(
appDataPath,
'workspaces',
'local',
workspaceId
);
await fs.ensureDir(workspacePath);
await trashWorkspace(
universalId({ peer: 'local', type: 'workspace', id: workspaceId })
);
expect(await fs.pathExists(workspacePath)).toBe(false);
// removed workspace will be moved to deleted-workspaces
expect(
await fs.pathExists(
path.join(appDataPath, 'deleted-workspaces', workspaceId)
)
).toBe(true);
});
test('delete workspace', async () => {
const { deleteWorkspace } =
await import('@affine/electron/helper/workspace/handlers');
const workspaceId = v4();
const workspacePath = path.join(
appDataPath,
'workspaces',
'local',
workspaceId
);
await fs.ensureDir(workspacePath);
await deleteWorkspace(
universalId({ peer: 'local', type: 'workspace', id: workspaceId })
);
expect(await fs.pathExists(workspacePath)).toBe(false);
// deleted workspace will remove it permanently
expect(
await fs.pathExists(
path.join(appDataPath, 'deleted-workspaces', workspaceId)
)
).toBe(false);
});
test.each([
{
name: 'deleting a workspace',
outsideDirName: 'outside-delete-target',
call: async () => {
const { deleteWorkspace } =
await import('@affine/electron/helper/workspace/handlers');
return deleteWorkspace(
universalId({
peer: 'local',
type: 'workspace',
id: '../../outside-delete-target',
})
);
},
},
{
name: 'deleting backup workspaces',
outsideDirName: 'outside-backup-target',
call: async () => {
const { deleteBackupWorkspace } =
await import('@affine/electron/helper/workspace/handlers');
return deleteBackupWorkspace('../../outside-backup-target');
},
},
{
name: 'recovering backup workspaces',
outsideDirName: 'outside-recover-target',
call: async () => {
const { recoverBackupWorkspace } =
await import('@affine/electron/helper/workspace/handlers');
return recoverBackupWorkspace('../../outside-recover-target');
},
},
])('rejects unsafe ids when $name', async ({ outsideDirName, call }) => {
const outsideDir = path.join(tmpDir, outsideDirName);
await fs.ensureDir(outsideDir);
await expect(call()).rejects.toThrow('Invalid workspace id');
expect(await fs.pathExists(outsideDir)).toBe(true);
});
});