dsh-workrally 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/lib/account.js +16 -0
- package/lib/catalog.js +109 -0
- package/lib/client.js +1661 -293
- package/lib/desk.js +10 -7
- package/lib/gallery.js +146 -14
- package/lib/index.js +237 -20
- package/lib/mcp.js +518 -0
- package/lib/plaza.js +155 -0
- package/package.json +1 -1
package/lib/desk.js
CHANGED
|
@@ -6,7 +6,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
6
6
|
import { existsSync, readFileSync } from 'node:fs';
|
|
7
7
|
import { homedir } from 'node:os';
|
|
8
8
|
import { join } from 'node:path';
|
|
9
|
-
import { assetsForTask, gallerySessions, listGallery, rememberGeneration, sessionIdFromExec, sourceList, writeStore } from './gallery.js';
|
|
9
|
+
import { assetsForTask, gallerySessions, listGallery, reloadGalleryIfChanged, rememberGeneration, sessionIdFromExec, sourceList, writeStore } from './gallery.js';
|
|
10
10
|
import { getConnection, isGenerationTool, isResultTool, normalizeToolResult, readNativeTask, workrallyTool } from './mcp.js';
|
|
11
11
|
|
|
12
12
|
const TERMINAL = new Set(['success', 'failed', 'cancelled']);
|
|
@@ -300,9 +300,12 @@ const listSessions = async (ctx) => {
|
|
|
300
300
|
};
|
|
301
301
|
|
|
302
302
|
/** GET 与 POST refresh 共用的快照;这里不发起任何远端请求。 */
|
|
303
|
-
export const getStudio = async (ctx, sessionId = '') =>
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
303
|
+
export const getStudio = async (ctx, sessionId = '') => {
|
|
304
|
+
reloadGalleryIfChanged();
|
|
305
|
+
return {
|
|
306
|
+
items: listGallery(sessionId),
|
|
307
|
+
tasks: listTasks(sessionId),
|
|
308
|
+
connection: await getConnection(ctx),
|
|
309
|
+
sessions: await listSessions(ctx),
|
|
310
|
+
};
|
|
311
|
+
};
|
package/lib/gallery.js
CHANGED
|
@@ -40,11 +40,28 @@ export const isAllowedGalleryMediaUrl = (value) => {
|
|
|
40
40
|
}
|
|
41
41
|
};
|
|
42
42
|
|
|
43
|
+
/** 任务回执里的 /s/ 短链是分享页,会过期并返回 HTML,不能当作图片或视频地址。 */
|
|
44
|
+
export const isShareMediaUrl = (value) => {
|
|
45
|
+
try {
|
|
46
|
+
const url = new URL(value);
|
|
47
|
+
return url.pathname === '/s' || url.pathname.startsWith('/s/');
|
|
48
|
+
} catch {
|
|
49
|
+
return false;
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
export const isDirectMediaUrl = value => isAllowedGalleryMediaUrl(value) && !isShareMediaUrl(value);
|
|
54
|
+
|
|
43
55
|
const safeFileName = value => typeof value === 'string' && /^[\w-][\w.-]*$/.test(value) ? value : '';
|
|
44
56
|
const clone = value => JSON.parse(JSON.stringify(value));
|
|
57
|
+
let storeMtime = 0;
|
|
45
58
|
export const configureGalleryStore = (file) => { storeFile = file; writable = true; };
|
|
46
59
|
export const resetGallery = () => { items.length = 0; };
|
|
47
|
-
const saveGallery = () => {
|
|
60
|
+
const saveGallery = () => {
|
|
61
|
+
if (!writable) return;
|
|
62
|
+
writeStore(storeFile, { version: 2, items });
|
|
63
|
+
try { storeMtime = statSync(storeFile).mtimeMs; } catch { /* 读不到时间时下次再判 */ }
|
|
64
|
+
};
|
|
48
65
|
|
|
49
66
|
/**
|
|
50
67
|
* 读取 v2 清单;旧数组清单只读迁移到另一个新文件,原文件永不改写。
|
|
@@ -78,12 +95,40 @@ export const loadGallery = (file, legacyFile) => {
|
|
|
78
95
|
if (source === storeFile) writable = false;
|
|
79
96
|
throw error;
|
|
80
97
|
}
|
|
98
|
+
try { storeMtime = statSync(storeFile).mtimeMs; } catch { storeMtime = 0; }
|
|
81
99
|
};
|
|
82
100
|
|
|
101
|
+
/**
|
|
102
|
+
* 清单文件被外部写入(例如 Agent 用独立 MCP 客户端生成)后热加载。
|
|
103
|
+
* 解析失败时保留当前内存清单,不影响正在展示的片库。
|
|
104
|
+
*/
|
|
105
|
+
export const reloadGalleryIfChanged = () => {
|
|
106
|
+
if (!storeFile || !existsSync(storeFile)) return false;
|
|
107
|
+
try {
|
|
108
|
+
const mtime = statSync(storeFile).mtimeMs;
|
|
109
|
+
if (mtime === storeMtime) return false;
|
|
110
|
+
const backup = items.slice();
|
|
111
|
+
const previousWritable = writable;
|
|
112
|
+
try {
|
|
113
|
+
loadGallery(storeFile);
|
|
114
|
+
} catch {
|
|
115
|
+
items.length = 0;
|
|
116
|
+
items.push(...backup);
|
|
117
|
+
writable = previousWritable;
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
return true;
|
|
121
|
+
} catch {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const fileSrc = item => `/workrally/file/${encodeURIComponent(item.id)}?session=${encodeURIComponent(item.sessionId || '')}`;
|
|
127
|
+
|
|
83
128
|
const publicItem = item => ({
|
|
84
129
|
id: item.id,
|
|
85
130
|
url: item.url,
|
|
86
|
-
src:
|
|
131
|
+
src: fileSrc(item),
|
|
87
132
|
local: Boolean(item.file),
|
|
88
133
|
mediaType: item.mediaType || 'image',
|
|
89
134
|
prompt: item.prompt || '',
|
|
@@ -161,8 +206,15 @@ export const rememberGeneration = (toolName, args, result, sessionId = '', metad
|
|
|
161
206
|
for (const asset of collectAssets(normalized.payloads)) {
|
|
162
207
|
const taskId = asset.taskId || metadata.taskId || '';
|
|
163
208
|
const known = typeof metadata.lookup === 'function' ? metadata.lookup(tool.serverName, taskId) || {} : {};
|
|
164
|
-
|
|
165
|
-
|
|
209
|
+
// 同一素材先按 assetId/URL 认领:提交回执与后续查询回执的 taskId 可能一个为空,
|
|
210
|
+
// 只按 taskId 比对会把同一次生成记成两条(一条带提示词、一条只剩素材标题)。
|
|
211
|
+
const sameScope = entry => entry.sessionId === sessionId
|
|
212
|
+
&& (!entry.serverName || entry.serverName === tool.serverName);
|
|
213
|
+
let item = items.find(entry => sameScope(entry)
|
|
214
|
+
&& (asset.assetId ? entry.assetId === asset.assetId : entry.url === asset.url));
|
|
215
|
+
if (!item && taskId) {
|
|
216
|
+
item = items.find(entry => sameScope(entry) && (entry.taskId || '') === taskId && !entry.assetId);
|
|
217
|
+
}
|
|
166
218
|
if (!item) {
|
|
167
219
|
item = { id: randomUUID(), at: new Date().toISOString(), file: '', prompt: '', model: '', sources: [], params: {} };
|
|
168
220
|
items.unshift(item);
|
|
@@ -171,7 +223,8 @@ export const rememberGeneration = (toolName, args, result, sessionId = '', metad
|
|
|
171
223
|
const pick = key => (own[key] && (!Array.isArray(own[key]) || own[key].length) ? own[key] : null)
|
|
172
224
|
?? (known[key] && (!Array.isArray(known[key]) || known[key].length) ? known[key] : null);
|
|
173
225
|
Object.assign(item, {
|
|
174
|
-
url: asset.url, mediaType: asset.mediaType, assetId: asset.assetId || item.assetId || '',
|
|
226
|
+
url: asset.url, mediaType: asset.mediaType, assetId: asset.assetId || item.assetId || '',
|
|
227
|
+
taskId: taskId || item.taskId || '',
|
|
175
228
|
sessionId, serverName: tool.serverName,
|
|
176
229
|
toolName: fromSubmit ? toolName : known.toolName || item.toolName || toolName,
|
|
177
230
|
prompt: pick('prompt') || item.prompt || asset.title || '',
|
|
@@ -274,23 +327,102 @@ export const readGalleryFile = (id, sessionId) => {
|
|
|
274
327
|
}
|
|
275
328
|
};
|
|
276
329
|
|
|
330
|
+
const findGalleryItem = (id, sessionId) => items.find(entry => entry.id === id && (!sessionId || entry.sessionId === sessionId));
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* 从 asset_detail 回执里取可下载地址。优先 download_url,跳过 /s/ 分享短链。
|
|
334
|
+
* 只采纳与 assetId 对应的那一条,避免把同页其他素材的地址拿来。
|
|
335
|
+
*/
|
|
336
|
+
export const pickAssetDownloadUrl = (payloads, assetId) => {
|
|
337
|
+
const want = String(assetId || '');
|
|
338
|
+
const ranked = [];
|
|
339
|
+
const visit = (node, matched, depth) => {
|
|
340
|
+
if (!node || typeof node !== 'object' || depth > 12) return;
|
|
341
|
+
if (Array.isArray(node)) {
|
|
342
|
+
node.forEach(entry => visit(entry, matched, depth + 1));
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
const id = String(node.asset_id || node.assetId || node.id || '');
|
|
346
|
+
const now = matched || Boolean(want && id === want);
|
|
347
|
+
const details = node.asset_details && typeof node.asset_details === 'object' ? node.asset_details : null;
|
|
348
|
+
if (now || !want) {
|
|
349
|
+
const bag = details || node;
|
|
350
|
+
const download = bag.download_url || bag.downloadUrl;
|
|
351
|
+
const page = bag.url || bag.cdn_url || bag.asset_url;
|
|
352
|
+
if (typeof download === 'string') ranked.push(download);
|
|
353
|
+
if (typeof page === 'string') ranked.push(page);
|
|
354
|
+
}
|
|
355
|
+
for (const [key, value] of Object.entries(node)) {
|
|
356
|
+
if (key === 'asset_details') continue;
|
|
357
|
+
if (value && typeof value === 'object') visit(value, now, depth + 1);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
(Array.isArray(payloads) ? payloads : []).forEach(payload => visit(payload, false, 0));
|
|
361
|
+
return ranked.find(isDirectMediaUrl) || '';
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
const storeGalleryMedia = (item, media) => {
|
|
365
|
+
if (!filesDir) return false;
|
|
366
|
+
mkdirSync(filesDir, { recursive: true });
|
|
367
|
+
const name = safeFileName(`${item.id}.${media.ext}`);
|
|
368
|
+
if (!name) return false;
|
|
369
|
+
const path = join(filesDir, name);
|
|
370
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
371
|
+
writeFileSync(temporary, media.bytes, { mode: 0o600 });
|
|
372
|
+
renameSync(temporary, path);
|
|
373
|
+
item.file = name;
|
|
374
|
+
return true;
|
|
375
|
+
};
|
|
376
|
+
|
|
277
377
|
/** 用户主动打开媒体后保存本地副本;内容已通过签名校验,失败不影响展示。 */
|
|
278
378
|
export const saveGalleryFile = (url, media) => {
|
|
279
379
|
if (!filesDir) return;
|
|
280
380
|
const pending = items.filter(item => item.url === url && !item.file);
|
|
281
381
|
if (!pending.length) return;
|
|
282
382
|
try {
|
|
283
|
-
|
|
284
|
-
for (const item of pending) {
|
|
285
|
-
const name = safeFileName(`${item.id}.${media.ext}`);
|
|
286
|
-
const path = join(filesDir, name);
|
|
287
|
-
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
288
|
-
writeFileSync(temporary, media.bytes, { mode: 0o600 });
|
|
289
|
-
renameSync(temporary, path);
|
|
290
|
-
item.file = name;
|
|
291
|
-
}
|
|
383
|
+
pending.forEach(item => storeGalleryMedia(item, media));
|
|
292
384
|
saveGallery();
|
|
293
385
|
} catch {
|
|
294
386
|
pending.forEach((item) => { item.file = ''; });
|
|
295
387
|
}
|
|
296
388
|
};
|
|
389
|
+
|
|
390
|
+
const materializing = new Map();
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* 本地没有副本时补一份。已存的签名地址先试一次;失败或只剩分享短链时,
|
|
394
|
+
* 用调用方提供的解析(通常是 asset_detail)换一条新的下载地址再落盘。
|
|
395
|
+
*/
|
|
396
|
+
export const materializeGalleryFile = async (id, sessionId, resolveUrl, signal) => {
|
|
397
|
+
const ready = readGalleryFile(id, sessionId);
|
|
398
|
+
if (ready) return ready;
|
|
399
|
+
const key = `${sessionId}\n${id}`;
|
|
400
|
+
const pending = materializing.get(key);
|
|
401
|
+
if (pending) return pending;
|
|
402
|
+
const job = (async () => {
|
|
403
|
+
const item = findGalleryItem(id, sessionId);
|
|
404
|
+
if (!item || signal?.aborted) return null;
|
|
405
|
+
let media = null;
|
|
406
|
+
if (isDirectMediaUrl(item.url)) {
|
|
407
|
+
try { media = await downloadGalleryMedia(item.url, signal); } catch { media = null; }
|
|
408
|
+
}
|
|
409
|
+
if (!media && item.assetId && typeof resolveUrl === 'function') {
|
|
410
|
+
let fresh = '';
|
|
411
|
+
try { fresh = await resolveUrl({ id: item.id, assetId: item.assetId, sessionId: item.sessionId, serverName: item.serverName || '' }); }
|
|
412
|
+
catch { fresh = ''; }
|
|
413
|
+
if (isDirectMediaUrl(fresh) && fresh !== item.url) {
|
|
414
|
+
try { media = await downloadGalleryMedia(fresh, signal); } catch { media = null; }
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (!media) return null;
|
|
418
|
+
try {
|
|
419
|
+
if (storeGalleryMedia(item, media)) saveGallery();
|
|
420
|
+
} catch {
|
|
421
|
+
item.file = '';
|
|
422
|
+
}
|
|
423
|
+
return { bytes: media.bytes, mime: media.mime };
|
|
424
|
+
})();
|
|
425
|
+
materializing.set(key, job);
|
|
426
|
+
try { return await job; }
|
|
427
|
+
finally { materializing.delete(key); }
|
|
428
|
+
};
|
package/lib/index.js
CHANGED
|
@@ -14,12 +14,15 @@ import {
|
|
|
14
14
|
listGallery,
|
|
15
15
|
listLineage,
|
|
16
16
|
loadGallery,
|
|
17
|
+
materializeGalleryFile,
|
|
18
|
+
pickAssetDownloadUrl,
|
|
17
19
|
readGalleryFile,
|
|
18
20
|
saveGalleryFile,
|
|
19
21
|
stopGalleryDownloads,
|
|
20
22
|
} from './gallery.js';
|
|
21
|
-
import { listInspiration } from './inspiration.js';
|
|
22
|
-
import { configureMcp } from './mcp.js';
|
|
23
|
+
import { listInspiration, resetInspiration } from './inspiration.js';
|
|
24
|
+
import { callNativeTool, configureMcp, downloadAssetFile, normalizeToolResult, readAssetDownloadTarget, readAssetPrompt, readNativeAssets, readNativeCanvases, resolveAssetPlaybackUrl } from './mcp.js';
|
|
25
|
+
import { listCollections, resetCollections } from './plaza.js';
|
|
23
26
|
import { registerWorkrallySkills } from './skills.js';
|
|
24
27
|
|
|
25
28
|
export const name = 'dsh-workrally';
|
|
@@ -110,24 +113,130 @@ const sessionParam = (value) => {
|
|
|
110
113
|
return !id || SESSION_ID.test(id) ? id : null;
|
|
111
114
|
};
|
|
112
115
|
|
|
116
|
+
/** 分享短链过期后,用素材 ID 向当前登录账号重取可下载地址。 */
|
|
117
|
+
const resolveAssetMediaUrl = async (ctx, record) => {
|
|
118
|
+
const serverName = /^[A-Za-z0-9_-]+$/.test(record?.serverName || '') ? record.serverName : 'workrally';
|
|
119
|
+
if (!record?.assetId) return '';
|
|
120
|
+
const result = await callNativeTool(ctx, {
|
|
121
|
+
serverName,
|
|
122
|
+
action: 'asset_detail',
|
|
123
|
+
args: { asset_ids: [record.assetId] },
|
|
124
|
+
sessionId: record.sessionId || '',
|
|
125
|
+
}, AbortSignal.timeout(20_000));
|
|
126
|
+
return pickAssetDownloadUrl(normalizeToolResult(result).payloads, record.assetId);
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const sendMedia = (res, file, cache) => {
|
|
130
|
+
res.writeHead(200, {
|
|
131
|
+
'content-type': file.mime,
|
|
132
|
+
'content-length': file.bytes.length,
|
|
133
|
+
'cache-control': cache,
|
|
134
|
+
'x-content-type-options': 'nosniff',
|
|
135
|
+
});
|
|
136
|
+
res.end(file.bytes);
|
|
137
|
+
};
|
|
138
|
+
|
|
113
139
|
const proxyMedia = async (res, target) => {
|
|
114
140
|
const controller = new AbortController();
|
|
115
141
|
res.on?.('close', () => controller.abort());
|
|
116
142
|
try {
|
|
117
143
|
const media = await downloadGalleryMedia(target, controller.signal);
|
|
118
144
|
saveGalleryFile(target, media);
|
|
119
|
-
res
|
|
120
|
-
'content-type': media.mime,
|
|
121
|
-
'content-length': media.bytes.length,
|
|
122
|
-
'cache-control': 'private, max-age=300',
|
|
123
|
-
'x-content-type-options': 'nosniff',
|
|
124
|
-
});
|
|
125
|
-
res.end(media.bytes);
|
|
145
|
+
sendMedia(res, media, 'private, max-age=300');
|
|
126
146
|
} catch (error) {
|
|
127
147
|
if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '媒体读取失败,请稍后重试' });
|
|
128
148
|
}
|
|
129
149
|
};
|
|
130
150
|
|
|
151
|
+
const MAX_BRIDGE_BODY = 32_768;
|
|
152
|
+
const bridgeHeaders = (req) => {
|
|
153
|
+
const origin = String(req?.headers?.origin || '');
|
|
154
|
+
const allowed = /^http:\/\/(127\.0\.0\.1|localhost)(:\d+)?$/i.test(origin) ? origin : 'http://127.0.0.1:8765';
|
|
155
|
+
return {
|
|
156
|
+
'access-control-allow-origin': allowed,
|
|
157
|
+
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
158
|
+
'access-control-allow-headers': 'content-type',
|
|
159
|
+
vary: 'Origin',
|
|
160
|
+
};
|
|
161
|
+
};
|
|
162
|
+
let queuedDraft = null;
|
|
163
|
+
let bridgeServer = null;
|
|
164
|
+
let bridgeView = null;
|
|
165
|
+
|
|
166
|
+
const readBridgeBody = req => new Promise((resolve, reject) => {
|
|
167
|
+
const chunks = [];
|
|
168
|
+
let size = 0;
|
|
169
|
+
req.on('data', (chunk) => {
|
|
170
|
+
size += chunk.length;
|
|
171
|
+
if (size > MAX_BRIDGE_BODY) {
|
|
172
|
+
reject(Object.assign(new Error('草稿过长'), { status: 413 }));
|
|
173
|
+
req.destroy();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
chunks.push(chunk);
|
|
177
|
+
});
|
|
178
|
+
req.on('end', () => {
|
|
179
|
+
try { resolve(JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')); }
|
|
180
|
+
catch { reject(Object.assign(new Error('请求不是 JSON'), { status: 400 })); }
|
|
181
|
+
});
|
|
182
|
+
req.on('error', reject);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
const startDraftBridge = async (log) => {
|
|
186
|
+
if (bridgeServer) return bridgeServer;
|
|
187
|
+
const { createServer } = await import('node:http');
|
|
188
|
+
const server = createServer(async (req, res) => {
|
|
189
|
+
const cors = bridgeHeaders(req);
|
|
190
|
+
const method = (req.method || 'GET').toUpperCase();
|
|
191
|
+
if (method === 'OPTIONS') {
|
|
192
|
+
res.writeHead(204, cors);
|
|
193
|
+
res.end();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const url = new URL(req.url || '/', 'http://127.0.0.1:47829');
|
|
197
|
+
if (method === 'GET' && url.pathname === '/canvases') {
|
|
198
|
+
try {
|
|
199
|
+
const data = await readNativeCanvases(bridgeView);
|
|
200
|
+
res.writeHead(200, { ...cors, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
201
|
+
res.end(JSON.stringify(data));
|
|
202
|
+
} catch (error) {
|
|
203
|
+
res.writeHead(502, { ...cors, 'content-type': 'application/json; charset=utf-8' });
|
|
204
|
+
res.end(JSON.stringify({ error: error?.message || '画布读取失败' }));
|
|
205
|
+
}
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (method !== 'POST' || url.pathname !== '/draft') {
|
|
209
|
+
res.writeHead(404, { ...cors, 'content-type': 'application/json; charset=utf-8' });
|
|
210
|
+
res.end('{"error":"not found"}');
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
const body = await readBridgeBody(req);
|
|
215
|
+
const text = typeof body?.text === 'string' ? body.text.trim() : '';
|
|
216
|
+
if (!text) {
|
|
217
|
+
res.writeHead(400, { ...cors, 'content-type': 'application/json; charset=utf-8' });
|
|
218
|
+
res.end('{"error":"empty"}');
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
queuedDraft = { id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, text, at: Date.now() };
|
|
222
|
+
res.writeHead(200, { ...cors, 'content-type': 'application/json; charset=utf-8' });
|
|
223
|
+
res.end(JSON.stringify({ ok: true, id: queuedDraft.id }));
|
|
224
|
+
} catch (error) {
|
|
225
|
+
res.writeHead(error?.status || 500, { ...cors, 'content-type': 'application/json; charset=utf-8' });
|
|
226
|
+
res.end(JSON.stringify({ error: error?.message || 'failed' }));
|
|
227
|
+
}
|
|
228
|
+
});
|
|
229
|
+
server.on('error', err => log?.('本地草稿桥端口占用', err));
|
|
230
|
+
server.listen(47829, '127.0.0.1');
|
|
231
|
+
bridgeServer = server;
|
|
232
|
+
return server;
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
const stopDraftBridge = () => {
|
|
236
|
+
try { bridgeServer?.close(); } catch { /* ignore */ }
|
|
237
|
+
bridgeServer = null;
|
|
238
|
+
};
|
|
239
|
+
|
|
131
240
|
/** 路由处理器。所有路由先过宿主准入,再按会话过滤数据。 */
|
|
132
241
|
export const createStudioHandler = ctx => async (req, res) => {
|
|
133
242
|
const url = new URL(req.url || '/', 'http://127.0.0.1');
|
|
@@ -150,6 +259,26 @@ export const createStudioHandler = ctx => async (req, res) => {
|
|
|
150
259
|
sendJson(res, 200, ctx.account.login());
|
|
151
260
|
return;
|
|
152
261
|
}
|
|
262
|
+
if (method === 'POST' && url.pathname === '/workrally/account/relogin') {
|
|
263
|
+
if (!isJson) {
|
|
264
|
+
sendJson(res, 415, { error: 'json required' });
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (!ctx.account) {
|
|
268
|
+
sendJson(res, 503, { error: 'account unavailable' });
|
|
269
|
+
return;
|
|
270
|
+
}
|
|
271
|
+
sendJson(res, 200, await ctx.account.relogin());
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (method === 'POST' && url.pathname === '/workrally/refresh') {
|
|
275
|
+
// Workbench 的「刷新全部」:先丢掉宿主端模板/灵感缓存,客户端随后
|
|
276
|
+
// 重新读取任务、画布与合集,避免拿到 10 分钟内的旧数据。
|
|
277
|
+
resetCollections();
|
|
278
|
+
resetInspiration();
|
|
279
|
+
sendJson(res, 200, { ok: true, at: Date.now() });
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
153
282
|
if (method === 'POST' && url.pathname === '/workrally/studio/refresh') {
|
|
154
283
|
if (!isJson) {
|
|
155
284
|
sendJson(res, 415, { error: 'json required' });
|
|
@@ -181,6 +310,85 @@ export const createStudioHandler = ctx => async (req, res) => {
|
|
|
181
310
|
}
|
|
182
311
|
return;
|
|
183
312
|
}
|
|
313
|
+
if (url.pathname === '/workrally/plaza') {
|
|
314
|
+
try {
|
|
315
|
+
sendJson(res, 200, { collections: await listCollections() });
|
|
316
|
+
} catch {
|
|
317
|
+
sendJson(res, 502, { error: '模版库暂时读取不到,请稍后重试' });
|
|
318
|
+
}
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
if (url.pathname === '/workrally/canvases') {
|
|
322
|
+
try {
|
|
323
|
+
sendJson(res, 200, await readNativeCanvases(ctx));
|
|
324
|
+
} catch (error) {
|
|
325
|
+
sendJson(res, 502, { error: error?.message || '画布列表暂时读取不到,请稍后重试' });
|
|
326
|
+
}
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (url.pathname === '/workrally/assets') {
|
|
330
|
+
try {
|
|
331
|
+
sendJson(res, 200, await readNativeAssets(ctx, {
|
|
332
|
+
page: url.searchParams.get('page') || 1,
|
|
333
|
+
materialType: url.searchParams.get('type') || '',
|
|
334
|
+
canvasId: url.searchParams.get('canvas') || '',
|
|
335
|
+
keyword: url.searchParams.get('q') || '',
|
|
336
|
+
}));
|
|
337
|
+
} catch (error) {
|
|
338
|
+
sendJson(res, 502, { error: error?.message || '媒资暂时读取不到,请稍后重试' });
|
|
339
|
+
}
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
if (url.pathname === '/workrally/assets/prompt') {
|
|
343
|
+
try {
|
|
344
|
+
const prompt = await readAssetPrompt(ctx, url.searchParams.get('id') || '', url.searchParams.get('canvas') || '');
|
|
345
|
+
sendJson(res, 200, { prompt });
|
|
346
|
+
} catch {
|
|
347
|
+
sendJson(res, 200, { prompt: '' });
|
|
348
|
+
}
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
if (url.pathname === '/workrally/assets/play') {
|
|
352
|
+
try {
|
|
353
|
+
const target = await readAssetDownloadTarget(ctx, url.searchParams.get('id') || '');
|
|
354
|
+
const media = await resolveAssetPlaybackUrl(target.url);
|
|
355
|
+
res.writeHead(302, {
|
|
356
|
+
location: media.url,
|
|
357
|
+
'cache-control': 'private, no-store',
|
|
358
|
+
'referrer-policy': 'no-referrer',
|
|
359
|
+
});
|
|
360
|
+
res.end();
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '视频暂时播放不了,请稍后重试' });
|
|
363
|
+
}
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
if (url.pathname === '/workrally/assets/file') {
|
|
367
|
+
try {
|
|
368
|
+
const target = await readAssetDownloadTarget(ctx, url.searchParams.get('id') || '');
|
|
369
|
+
const file = await downloadAssetFile(target.url);
|
|
370
|
+
const ext = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov', 'audio/wav': 'wav', 'audio/wave': 'wav', 'audio/mpeg': 'mp3', 'audio/mp4': 'm4a' }[file.mime] || 'bin';
|
|
371
|
+
const base = String(target.title || url.searchParams.get('id') || 'workrally').replace(/[\\/:*?"<>|\r\n]+/g, ' ').trim().slice(0, 80) || 'workrally';
|
|
372
|
+
const filename = `${base}.${ext}`;
|
|
373
|
+
res.writeHead(200, {
|
|
374
|
+
'content-type': file.mime,
|
|
375
|
+
'content-length': file.bytes.length,
|
|
376
|
+
'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename)}`,
|
|
377
|
+
'cache-control': 'private, no-store',
|
|
378
|
+
'x-content-type-options': 'nosniff',
|
|
379
|
+
});
|
|
380
|
+
res.end(file.bytes);
|
|
381
|
+
} catch (error) {
|
|
382
|
+
if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '下载失败,请稍后重试' });
|
|
383
|
+
}
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (url.pathname === '/workrally/draft/Consume') {
|
|
387
|
+
const item = queuedDraft && Date.now() - queuedDraft.at < 30_000 ? queuedDraft : null;
|
|
388
|
+
queuedDraft = null;
|
|
389
|
+
sendJson(res, 200, { draft: item });
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
184
392
|
if (url.pathname.startsWith('/workrally/file/')) {
|
|
185
393
|
let id = '';
|
|
186
394
|
try {
|
|
@@ -188,18 +396,22 @@ export const createStudioHandler = ctx => async (req, res) => {
|
|
|
188
396
|
} catch {
|
|
189
397
|
// 按不存在处理
|
|
190
398
|
}
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
399
|
+
const session = url.searchParams.get('session') || '';
|
|
400
|
+
const cached = readGalleryFile(id, session);
|
|
401
|
+
if (cached) {
|
|
402
|
+
sendMedia(res, cached, 'private, max-age=86400');
|
|
194
403
|
return;
|
|
195
404
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
405
|
+
try {
|
|
406
|
+
const file = await materializeGalleryFile(id, session, record => resolveAssetMediaUrl(ctx, record));
|
|
407
|
+
if (!file) {
|
|
408
|
+
sendJson(res, 404, { error: 'not found' });
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
sendMedia(res, file, 'private, max-age=86400');
|
|
412
|
+
} catch (error) {
|
|
413
|
+
if (!res.headersSent) sendJson(res, error?.status || 502, { error: error?.status ? error.message : '媒体读取失败,请稍后重试' });
|
|
414
|
+
}
|
|
203
415
|
return;
|
|
204
416
|
}
|
|
205
417
|
const session = sessionParam(url.searchParams.get('session') || '');
|
|
@@ -242,14 +454,19 @@ export const apply = (ctx, config = {}) => {
|
|
|
242
454
|
configureGalleryFiles(join(home, 'workrally-gallery-files'));
|
|
243
455
|
|
|
244
456
|
const account = createAccount({ warn: log });
|
|
457
|
+
const view = hostView(ctx, account);
|
|
458
|
+
bridgeView = view;
|
|
459
|
+
startDraftBridge(log).catch(() => {});
|
|
245
460
|
ctx.effect(() => () => {
|
|
246
461
|
account.stop();
|
|
247
462
|
stopDesk();
|
|
248
463
|
stopGalleryDownloads();
|
|
464
|
+
stopDraftBridge();
|
|
465
|
+
bridgeView = null;
|
|
249
466
|
}, 'dsh-workrally.stop');
|
|
250
467
|
ctx.effect(() => ctx.on('tools/result', observeToolResult), 'dsh-workrally.observe');
|
|
251
468
|
ctx.effect(
|
|
252
|
-
() => ctx.webServer.register({ kind: 'prefix', path: '/workrally', handler: guarded(
|
|
469
|
+
() => ctx.webServer.register({ kind: 'prefix', path: '/workrally', handler: guarded(view, log) }),
|
|
253
470
|
'dsh-workrally.route',
|
|
254
471
|
);
|
|
255
472
|
|