ai_co_discuss 0.5.21 → 0.5.23

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.
Files changed (85) hide show
  1. package/.agents/skills/codiscuss-draft-cleanup/SKILL.md +16 -0
  2. package/.agents/skills/codiscuss-draft-cleanup/cleanup.py +70 -0
  3. package/.agents/skills/codiscuss-draft-cleanup/scan.py +70 -0
  4. package/.agents/skills/discuss-host/references/control.md +2 -2
  5. package/.agents/skills/discuss-host/references/workflow.md +4 -2
  6. package/.agents/skills/discuss-participant/SKILL.md +2 -0
  7. package/.agents/skills/local-stt-setup/SKILL.md +9 -8
  8. package/.agents/skills/local-tts-setup/SKILL.md +10 -9
  9. package/.agents/skills/share-card/SKILL.md +7 -6
  10. package/.agents/skills/share-card/references/share-card.md +34 -8
  11. package/.agents/skills/workflow-creator/SKILL.md +22 -14
  12. package/README.md +2 -0
  13. package/README.zh-CN.md +2 -0
  14. package/backend/free_room.py +64 -8
  15. package/backend/message_queue.py +9 -0
  16. package/backend/schema.sql +13 -1
  17. package/backend/server.py +289 -59
  18. package/docs/en/guide/admin.md +18 -0
  19. package/docs/en/guide/members.md +7 -1
  20. package/docs/en/guide/remote.md +1 -1
  21. package/docs/en/guide/rooms.md +14 -6
  22. package/docs/en/guide/voice.md +2 -0
  23. package/docs/en/guide/workflows.md +9 -5
  24. package/docs/en/guide/working.md +6 -4
  25. package/docs/guide/admin.md +18 -0
  26. package/docs/guide/members.md +7 -1
  27. package/docs/guide/remote.md +1 -1
  28. package/docs/guide/rooms.md +13 -6
  29. package/docs/guide/voice.md +2 -0
  30. package/docs/guide/workflows.md +9 -5
  31. package/docs/guide/working.md +6 -4
  32. package/frontend/locales/en/admin.json +58 -1
  33. package/frontend/locales/en/app.json +18 -1
  34. package/frontend/locales/en/backend.json +6 -0
  35. package/frontend/locales/en/core.json +4 -2
  36. package/frontend/locales/en/discussion.json +4 -1
  37. package/frontend/locales/en/room.json +85 -1
  38. package/gateway/gateway.mjs +49 -9
  39. package/package.json +3 -1
  40. package/runner/account_space.mjs +10 -0
  41. package/runner/adapters/antigravity_app.mjs +31 -4
  42. package/runner/adapters/antigravity_cli.mjs +9 -2
  43. package/runner/adapters/api.mjs +3 -2
  44. package/runner/adapters/api_pi.mjs +3 -2
  45. package/runner/adapters/api_pi_extension.mjs +5 -3
  46. package/runner/adapters/claude.mjs +32 -9
  47. package/runner/adapters/cli.mjs +2 -2
  48. package/runner/adapters/codex_app.mjs +192 -69
  49. package/runner/adapters/codex_cli.mjs +10 -5
  50. package/runner/adapters/common.mjs +414 -11
  51. package/runner/adapters/index.mjs +6 -0
  52. package/runner/admin_cli.mjs +22 -5
  53. package/runner/admin_panel.mjs +118 -5
  54. package/runner/admin_storage.mjs +105 -0
  55. package/runner/discussion_launch.mjs +328 -128
  56. package/runner/discussion_runner.mjs +12 -3
  57. package/runner/discussion_service.mjs +224 -37
  58. package/runner/discussion_skills.mjs +1 -1
  59. package/runner/expert_prompts.mjs +2 -2
  60. package/runner/experts.mjs +227 -0
  61. package/runner/file_diff.mjs +1 -1
  62. package/runner/free_runner.mjs +236 -51
  63. package/runner/i18n_en.mjs +39 -0
  64. package/runner/os_users.mjs +33 -1
  65. package/runner/project_files.mjs +7 -1
  66. package/runner/project_migration.mjs +245 -0
  67. package/runner/relay_channel.mjs +1 -1
  68. package/runner/remote_launch.mjs +4 -3
  69. package/runner/share_card.mjs +17 -1
  70. package/runner/share_shared.mjs +26 -9
  71. package/runner/site_deploy.mjs +2 -1
  72. package/runner/slash_names.mjs +12 -1
  73. package/runner/speech_directories.mjs +20 -0
  74. package/runner/storage_guard.mjs +383 -0
  75. package/runner/tts_providers.mjs +22 -21
  76. package/runner/workflows.mjs +211 -57
  77. package/web/admin.css +1 -1
  78. package/web/admin.js +8 -8
  79. package/web/app.js +589 -80
  80. package/web/i18n.js +4 -4
  81. package/web/markdown.css +1 -1
  82. package/web/modern.css +1 -1
  83. package/web/modern.js +68 -66
  84. package/workflows/decision-council/flow.json +216 -25
  85. package/workflows/trpg-classic/flow.json +151 -21
package/web/app.js CHANGED
@@ -365,6 +365,22 @@ function create_share_core({ t, display_name, collapse_visual_fences, is_text_at
365
365
  return String(text || "").replace(/```[\s\S]*?```/g, " ").replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/[`*_>#|~-]+/g, " ").replace(/\s+/g, " ").trim();
366
366
  }
367
367
 
368
+ /** One concise lead sentence (or two short ones) from the opening paragraph, leaving bullet checklists and prompt tails off the card. */
369
+ function share_card_lead(text, max_chars = 160) {
370
+ const first_para = String(text || "").replace(/\r\n/g, "\n").trim()
371
+ .split(/\n\s*\n|\n\s*(?:[-*•]|\d+[.)、])\s+/)[0];
372
+ const clean = share_plain(first_para).replace(/^(?:@\S+\s+)+/, "").trim();
373
+ if (!clean) return "";
374
+ const sentences = clean.match(/[^。!?.!?]+(?:[。!?]|[.!?](?=\s|$)|$)/gu) || [];
375
+ const first = sentences[0]?.trim() || "";
376
+ if (!first) return clean.slice(0, max_chars);
377
+ if (first.length < 10 && sentences[1]) {
378
+ const two = `${first}${/[a-zA-Z0-9.!?]$/.test(first) ? " " : ""}${sentences[1].trim()}`;
379
+ if (two.length <= max_chars) return two;
380
+ }
381
+ return first.slice(0, max_chars);
382
+ }
383
+
368
384
  function share_card_messages(responses) {
369
385
  return Object.entries(responses).filter(([path]) => /\/messages\?/.test(path)).flatMap(([, body]) => body.messages || [])
370
386
  .filter(message => message.kind !== "system" && message.text).sort((a, b) => a.id - b.id);
@@ -380,19 +396,20 @@ function create_share_core({ t, display_name, collapse_visual_fences, is_text_at
380
396
  const room = draft.responses[`/api/rooms/${draft.room_id}`] || {};
381
397
  const members = (room.members || []).filter(member => member.status !== "removed").map(member => member.label || display_name(member.name));
382
398
  const messages = share_card_messages(draft.responses);
383
- const question = messages.find(message => message.author === "用户" && !is_share_question_receipt(message.text)
384
- && !/^\/?(?:继续|好的?|同意|continue|ok)[。.!!\s]*$/iu.test(message.text.trim()));
399
+ const question = messages.find(message => {
400
+ if (message.author !== "用户") return false;
401
+ const body = String(message.text || "").trim();
402
+ if (!body || is_share_question_receipt(body) || /^\/(?:goal|discuss)\b/i.test(body)) return false;
403
+ return !/^\/?(?:继续|好的?|行|ok|yes|收到|同意|开始|可以|确认|嗯|明白|go|continue)[。.!!,,\s]*$/iu.test(body);
404
+ });
385
405
  const answers = messages.filter(message => message.author !== "用户" && message.author !== "系统" && message.id > (question?.id ?? 0));
386
406
  const outcome = answers.findLast(message => message.summary) || answers.at(-1);
387
407
  // Text the owner was asked to check stays off the card, which cannot be taken back once posted; it can be typed in.
388
408
  const flagged = new Set((draft.spots || []).map(spot => spot.where));
389
- const text = (message, value) => message && !flagged.has(`#${message.id}`) ? share_plain(value) : "";
390
- const result = text(outcome, outcome?.summary || outcome?.text);
391
- const sentences = result.match(/[^。!?.!?]+(?:[。!?]|[.!?](?=\s|$)|$)/gu) || [];
392
- const complete = sentences[0]?.trim();
393
- return { title: draft.title, members, materials: { through: messages.at(-1)?.id ?? null, count: messages.length },
394
- question: text(question, question?.text).slice(0, 600),
395
- outcome: (complete && result.startsWith(complete) ? complete : result).slice(0, 600),
409
+ const lead = (message, value, limit) => message && !flagged.has(`#${message.id}`) ? share_card_lead(value, limit) : "";
410
+ return { title: draft.title, members, card_version: 2, materials: { through: messages.at(-1)?.id ?? null, count: messages.length },
411
+ question: lead(question, question?.text, 160),
412
+ outcome: lead(outcome, outcome?.summary || outcome?.text, 200),
396
413
  stats: t('{members} 位 AI · {messages} 条消息 · {runs} 次执行', { members: members.length, messages: room.message_count ?? messages.length, runs: draft.runs ?? 0 }),
397
414
  url: link.url, expires: t('{time} 前有效', { time: new Date(link.expires_at).toLocaleString(undefined, { hour12: false }) }) };
398
415
  }
@@ -601,7 +618,7 @@ const RELAY_CIPHER_INFO = "codiscuss-relay-v1";
601
618
  // The rooms kept on the paired computer are read and written through its relay connection; only room routes go there.
602
619
  const RELAY_PROTOCOL = "codiscuss-relay";
603
620
  const RELAY_PING_MS = 25000;
604
- const ROOM_RELAY_PATH = /^\/api\/(rooms|folders|revisions)(\/|\?|$)/;
621
+ const ROOM_RELAY_PATH = /^\/api\/(rooms|folders|revisions|sites)(\/|\?|$)/;
605
622
  // One part is base64-encoded, encrypted and base64-encoded again (about 16/9 of its size), and the sealed request
606
623
  // must stay inside the hosted site's 512 KiB request limit (backend/worker.mjs MAX_BODY_BYTES). Parts stay small enough
607
624
  // for a slow phone network to carry one well inside its wait: 256 KiB parts took 3.4 s each on a phone, and one that ran
@@ -662,7 +679,7 @@ const MANUAL_TRIGGER_INSTRUCTION = "首次复制后,可由人工或软件原
662
679
  const MANAGEMENT_LOGIN_HINT = t('需要登录管理员账号或使用创建该房间的浏览器');
663
680
  const THEMES = ["channel", "channel-light"];
664
681
  // proxy and host_proxy label answers relayed for the retired web chatbot members.
665
- const SOURCE_LABELS = { demo: t('示例'), user: t('本人发言'), proxy: t('用户代发'), cli: t('CLI 发言'), api: t('API 发言'), url: t('历史 URL 发言'), host_proxy: t('主持人代发'), goal: "Goal" };
682
+ const SOURCE_LABELS = { room_relay_sent: t('跨房发送'), demo: t('示例'), user: t('本人发言'), proxy: t('用户代发'), cli: t('CLI 发言'), api: t('API 发言'), url: t('历史 URL 发言'), host_proxy: t('主持人代发'), goal: "Goal" };
666
683
  const TURN_LABELS = { pending: t('待处理'), notified: t('已通知,待回答'), answered: t('已回答'), cancelled: t('已取消') };
667
684
  const PLATFORM_IDENTITIES = {
668
685
  "用户": { label: "User", initials: "U", style: "user", icon: "/icons/user.svg", description: t('发起与协助') },
@@ -727,6 +744,8 @@ const ROOM_CACHE_LIMIT = 12;
727
744
  const room_views = new Map();
728
745
  // Member settings read for a new room before it opens, used once by its first load_room_models.
729
746
  const preloaded_room_models = new Map();
747
+ const recent_room_models = new Map();
748
+ const ROOM_MODELS_FRESH_MS = 30000;
730
749
  // How long a new room's placeholder waits for the room's content before opening it anyway.
731
750
  const ROOM_PRELOAD_LIMIT_MS = 4000;
732
751
  const message_histories = new Map();
@@ -813,7 +832,7 @@ state.navigation_version = 0;
813
832
  state.admin = { loaded: false, local: false, registered: false, setup_available: false, logged_in: false, profile: null, identity_version: 0 };
814
833
  // needs: "" | "pairing" | "renew"; pairing_code arrives from a scanned link (#pair=CODE); prompt waits for the user's tap.
815
834
  state.device = { id: "", needs: "", pairing_code: "", pairing_fp: "", prompt: null };
816
- state.launch = { available: false, remote: false, relay: null, connect_command: "", profiles: {}, projects: [], presets: [], builtin_presets: [], hidden_builtins: [], skilled_presets: [], workflows: [], description_templates: {}, workspace: {}, scheduler: {}, create_preferences: {}, error: "", recoveries: [] };
835
+ state.launch = { available: false, remote: false, relay: null, connect_command: "", profiles: {}, projects: [], presets: [], project_presets: [], create_project_roots: [], builtin_presets: [], hidden_builtins: [], skilled_presets: [], skilled_project_presets: [], workflows: [], project_workflows: [], project_roots: [], workflow_trust_prompt: null, description_templates: {}, workspace: {}, scheduler: {}, create_preferences: {}, storage: null, storage_loading: false, storage_error: "", storage_read_at: 0, storage_cleaning: [], error: "", recoveries: [] };
817
836
  state.create_host_workflows = false;
818
837
  state.create_host_permissions = null;
819
838
  // Mirrors DEFAULT_API_MAX_REQUESTS in runner/adapters/profiles.mjs; this classic script cannot import it.
@@ -1900,12 +1919,18 @@ async function move_folder({ id, before_id, direction }) {
1900
1919
  } finally { state.folder_order_pending = false; publish_view(); }
1901
1920
  }
1902
1921
 
1922
+ function directory_parent(room, rooms) {
1923
+ const parent = rooms.find(item => item.id === room?.parent_room_id && !item.archived);
1924
+ return parent && (parent.folder_id || "") === (room.folder_id || "") ? parent.id : null;
1925
+ }
1926
+
1903
1927
  /** Move a channel by one visible slot, also available without drag support. */
1904
1928
  async function move_channel({ id, direction, folder_id }) {
1905
1929
  if (state.directory_sort === "recent") return;
1906
1930
  const rooms = visible_rooms();
1907
1931
  const folder_scoped = folder_id !== undefined;
1908
- const group = folder_scoped ? rooms.filter((room) => (room.folder_id || null) === folder_id) : rooms;
1932
+ const parent = directory_parent(rooms.find(room => room.id === id), rooms);
1933
+ const group = rooms.filter(room => (!folder_scoped || (room.folder_id || null) === folder_id) && directory_parent(room, rooms) === parent);
1909
1934
  const index = group.findIndex((room) => room.id === id);
1910
1935
  if (index < 0 || (direction < 0 ? index === 0 : index === group.length - 1)) return;
1911
1936
  const without_room = rooms.filter((room) => room.id !== id);
@@ -1977,6 +2002,7 @@ function render_host_brief() {
1977
2002
 
1978
2003
  /** Describe roles separately from authors and the actual submitter. */
1979
2004
  function message_provenance(message) {
2005
+ if (message.relay_room) return t('来自房间「{room}」的主持人 {host}', { room: message.relay_title ?? t('已删除的房间'), host: message.relay_host });
1980
2006
  const role = message.kind === "receipt" ? t('运行回执') : message.kind === "moderation" ? t('主持发言') : (message.author === "用户" ? t('用户发言') : t('专家观点'));
1981
2007
  const forwarding = message.submitted_by && message.submitted_by !== message.author ? t(' · {value1} 代发', { value1: display_name(message.submitted_by) }) : "";
1982
2008
  return `${role}${forwarding}`;
@@ -1993,6 +2019,7 @@ function rendered_on_read(shown, message) {
1993
2019
  return Object.defineProperties(shown, {
1994
2020
  rendered_text: { enumerable: true, configurable: true, get: () => read_body().rendered_text },
1995
2021
  visual_blocks: { enumerable: true, configurable: true, get: () => read_body().visual_blocks },
2022
+ inline_images: { enumerable: true, configurable: true, get: () => read_body().inline_images },
1996
2023
  rendered_summary: { enumerable: true, configurable: true, get: () => summary ??= render_room_markdown(message.summary || "", { visual_label: t('交互式可视化') }) },
1997
2024
  });
1998
2025
  }
@@ -2139,6 +2166,12 @@ async function read_background_room(room_id, mark) {
2139
2166
  if (!history || !wanted()) return;
2140
2167
  cache_room_entry(room_views, room_id, room);
2141
2168
  background_reads.marks.set(room_id, mark);
2169
+ if (state.launch.available && !recent_room_models.has(room_id) && !preloaded_room_models.has(room_id)) {
2170
+ const models = await local_launch_request("room-models", { room_id, quick: true });
2171
+ if (wanted() && models.room_id === room_id) {
2172
+ cache_room_entry(recent_room_models, room_id, { ...room_models_fields(models), room_id, revision: "", loading: false });
2173
+ }
2174
+ }
2142
2175
  } catch (error) {
2143
2176
  // Nothing on screen depends on this read. A refused room waits for its next change; a network failure retries on the next directory read.
2144
2177
  if (error.preflight && wanted()) background_reads.marks.set(room_id, mark);
@@ -2355,6 +2388,11 @@ async function select_room(room_id) {
2355
2388
  const listed = state.rooms.find((room) => room.id === room_id);
2356
2389
  // A room opened before is shown as last read, with the directory's newer title, folder and archive state, until the site answers.
2357
2390
  const cached = listed && room_views.get(room_id);
2391
+ const leaving = state.launch.room_models;
2392
+ if (leaving?.participants && leaving.room_id === state.room?.id) {
2393
+ const incomplete = leaving.loading || Object.values(leaving.participants).some(profile => profile.defaults_pending);
2394
+ cache_room_entry(recent_room_models, leaving.room_id, { ...leaving, loading: false, revision: incomplete ? "" : leaving.revision });
2395
+ }
2358
2396
  state.room = cached ? { ...cached, ...listed } : listed;
2359
2397
  state.upload_status = "";
2360
2398
  state.sending_preview = null;
@@ -2370,7 +2408,13 @@ async function select_room(room_id) {
2370
2408
  for (const stashed of state.stashed_drafts) release_files(stashed.drafts);
2371
2409
  state.stashed_drafts = [];
2372
2410
  state.launch.repair = null;
2373
- state.launch.room_models = null;
2411
+ state.launch.workflow_trust_prompt = null;
2412
+ state.launch.room_models = listed && recent_room_models.get(room_id) || null;
2413
+ state.launch.project_workflows = state.launch.room_models?.project_workflows || [];
2414
+ state.launch.project_roots = state.launch.room_models?.project_roots || [];
2415
+ if (state.launch.room_models && Date.now() - (state.launch.room_models.read_at || 0) >= ROOM_MODELS_FRESH_MS) {
2416
+ state.launch.room_models.revision = "";
2417
+ }
2374
2418
  state.messages = [];
2375
2419
  state.message_history = null;
2376
2420
  state.history_cards = null;
@@ -2493,9 +2537,10 @@ function render_room_markdown(text, options = {}) {
2493
2537
  function render_message_body(message) {
2494
2538
  const visual_blocks = [];
2495
2539
  const visual_label = message.author !== "用户" && message.kind !== "receipt" || SHARE ? t('交互式可视化') : "";
2540
+ const inlined = new Set();
2496
2541
  const rendered_text = link_attachment_placeholders(render_room_markdown(message.text,
2497
- { visual_label, visual_blocks: SHARE ? undefined : visual_blocks }), message.attachments);
2498
- return { rendered_text, visual_blocks };
2542
+ { visual_label, visual_blocks: SHARE ? undefined : visual_blocks }), message.attachments, inlined);
2543
+ return { rendered_text, visual_blocks, inline_images: [...inlined] };
2499
2544
  }
2500
2545
 
2501
2546
  /**
@@ -2678,10 +2723,94 @@ async function move_browser_description_templates() {
2678
2723
  } catch (error) { console.warn("Moving description templates failed:", error.message); }
2679
2724
  }
2680
2725
 
2726
+ /** Composite key for a workflow across global and project scopes. */
2727
+ function workflow_key(item) {
2728
+ if (!item) return "";
2729
+ return item.scope === "project" ? `project:${item.project_id || ""}:${item.id}` : `global:${item.id}`;
2730
+ }
2731
+
2732
+ /** Composite key for an expert preset across global and project scopes. */
2733
+ function preset_key(item) {
2734
+ if (!item) return "";
2735
+ return item.scope === "project" ? `project:${item.project_id || ""}:${item.name}` : `global:${item.name}`;
2736
+ }
2737
+
2738
+ /** Merge a presets/workflows response back into local launch state and active room models when applicable. */
2739
+ function apply_presets_result(result, context = {}) {
2740
+ if (!result || typeof result !== "object") return;
2741
+ const patch = {};
2742
+ if (Array.isArray(result.presets)) patch.presets = result.presets.map(item => ({ scope: "global", ...item }));
2743
+ if (result.description_templates) patch.description_templates = result.description_templates;
2744
+ if (Array.isArray(result.builtin_presets)) patch.builtin_presets = result.builtin_presets;
2745
+ if (Array.isArray(result.hidden_builtins)) patch.hidden_builtins = result.hidden_builtins;
2746
+ if (Array.isArray(result.skilled_presets)) patch.skilled_presets = result.skilled_presets;
2747
+ if (Array.isArray(result.skilled_project_presets)) patch.skilled_project_presets = result.skilled_project_presets;
2748
+ if (Array.isArray(result.project_presets)) {
2749
+ const project_list = result.project_presets.map(item => ({ scope: "project", ...item }));
2750
+ if (context.room_id && state.launch.room_models?.room_id === context.room_id) {
2751
+ state.launch.room_models.project_experts = project_list;
2752
+ if (Array.isArray(result.project_roots)) state.launch.room_models.project_roots = result.project_roots;
2753
+ } else if (!context.room_id) {
2754
+ patch.project_presets = project_list;
2755
+ if (Array.isArray(result.project_roots)) patch.create_project_roots = result.project_roots;
2756
+ }
2757
+ } else if (!context.room_id && Array.isArray(result.project_roots)) {
2758
+ patch.create_project_roots = result.project_roots;
2759
+ }
2760
+ Object.assign(state.launch, patch);
2761
+ publish_view();
2762
+ }
2763
+
2764
+ /** Load global + project presets for the given directory/project/room context. */
2765
+ async function load_project_presets({ cwd = "", extra_directories = [], project_id = "", room_id = "" } = {}) {
2766
+ if (!state.launch.available) return null;
2767
+ const extras = (extra_directories || []).map(item => typeof item === "string" ? { path: item.trim() } : item).filter(item => item?.path);
2768
+ const payload = { action: "list", ...(room_id ? { room_id } : {}), ...(project_id ? { project_id } : {}),
2769
+ ...(cwd ? { cwd } : {}), ...(extras.length ? { extra_directories: extras } : {}) };
2770
+ const result = await local_launch_request("presets", payload);
2771
+ apply_presets_result(result, { room_id });
2772
+ return result;
2773
+ }
2774
+
2775
+ /** Clear new-room project presets when the form's project directory is cleared. */
2776
+ function clear_project_presets() {
2777
+ if (!state.launch.project_presets.length && !state.launch.create_project_roots.length) return;
2778
+ state.launch.project_presets = [];
2779
+ state.launch.create_project_roots = [];
2780
+ publish_view();
2781
+ }
2782
+
2783
+ /** Project presets for the active context: the room's project experts, or the create form's project presets. */
2784
+ function project_presets(room_id = "") {
2785
+ if (room_id) {
2786
+ const models = state.launch.room_models?.room_id === room_id ? state.launch.room_models : null;
2787
+ return models?.project_experts || [];
2788
+ }
2789
+ return state.launch.project_presets || [];
2790
+ }
2791
+
2792
+ /** Whether a preset (global or project) has its own skills directory. */
2793
+ function preset_skilled(preset) {
2794
+ if (!preset) return false;
2795
+ if (Array.isArray(preset.skills) && preset.skills.length) return true;
2796
+ if (preset.scope === "project") {
2797
+ return (state.launch.skilled_project_presets || []).includes(preset_key(preset));
2798
+ }
2799
+ return (state.launch.skilled_presets || []).includes(preset.name);
2800
+ }
2801
+
2681
2802
  /** Import an expert as a preset (`import_expert` in the local service) and keep the presets it leaves; the result says the rest. */
2682
2803
  async function import_expert(input) {
2683
2804
  const result = await local_launch_request("workflows", { action: "import-expert", ...input });
2684
- await load_launch_settings();
2805
+ if (result.presets || result.project_presets) {
2806
+ apply_presets_result(result, { room_id: input?.room_id || "" });
2807
+ } else {
2808
+ await load_launch_settings();
2809
+ }
2810
+ if (input?.scope === "project") {
2811
+ if (input.room_id && state.room?.id === input.room_id) await reload_room_models().catch(() => {});
2812
+ else if (input.cwd || input.project_id) await load_project_presets({ cwd: input.cwd, extra_directories: input.extra_directories, project_id: input.project_id }).catch(() => {});
2813
+ }
2685
2814
  return result;
2686
2815
  }
2687
2816
 
@@ -2692,22 +2821,21 @@ async function import_expert(input) {
2692
2821
  */
2693
2822
  async function save_card_preset(input) {
2694
2823
  const result = await local_launch_request("workflows", { action: "save-preset", ...input });
2695
- Object.assign(state.launch, { presets: result.presets, builtin_presets: result.builtin_presets || [], hidden_builtins: result.hidden_builtins || [], skilled_presets: result.skilled_presets || [] });
2696
- publish_view();
2824
+ apply_presets_result(result, { room_id: input?.room_id || "" });
2825
+ if (input?.target_scope === "project" && state.room?.id) await reload_room_models().catch(() => {});
2697
2826
  return { preset: result.preset, knowledge: result.knowledge };
2698
2827
  }
2699
2828
 
2700
2829
  /** Save the user's presets, default descriptions and/or deleted built-ins in the local service and keep its answer. */
2701
- async function save_presets(input) {
2830
+ async function save_presets(input, context = {}) {
2702
2831
  const result = await local_launch_request("presets", input);
2703
- Object.assign(state.launch, { presets: result.presets, description_templates: result.description_templates,
2704
- builtin_presets: result.builtin_presets || [], hidden_builtins: result.hidden_builtins || [], skilled_presets: result.skilled_presets || [] });
2705
- publish_view();
2832
+ apply_presets_result(result, context);
2833
+ return result;
2706
2834
  }
2707
2835
 
2708
2836
  // Expert presets: a named instance with its description, prompt and project access, added in one click.
2709
2837
  // The user's own preset replaces a built-in one of the same name.
2710
- /** Every preset the add row offers: built-in ones first, then the user's. */
2838
+ /** Every global preset the add row offers: built-in ones first, then the user's. */
2711
2839
  function expert_presets() {
2712
2840
  const own = new Set(state.launch.presets.map(preset => preset.name));
2713
2841
  return [...state.launch.builtin_presets.filter(preset => !own.has(preset.name)), ...state.launch.presets];
@@ -2726,19 +2854,47 @@ function apply_expert_preset(name, preset) {
2726
2854
  const { session_id, system_prompt, ...base } = state.launch.profiles[platform_of(name)] || {};
2727
2855
  const profile = { ...structuredClone(base), project_access: full_only_hint(base.adapter) ? "full" : preset.project_access || "read" };
2728
2856
  for (const field of ["model", "effort", "system_prompt"]) if (Object.hasOwn(preset, field)) profile[field] = preset[field];
2857
+ if (!preset._from_workflow && preset.scope === "project") {
2858
+ profile.preset_scope = "project";
2859
+ if (preset.project_id) profile.preset_project_id = preset.project_id;
2860
+ } else {
2861
+ if (preset._from_workflow) delete profile.preset_scope;
2862
+ else profile.preset_scope = "global";
2863
+ delete profile.preset_project_id;
2864
+ }
2729
2865
  state.launch.profiles[name] = profile;
2730
2866
  description_drafts[name] = preset.description || "";
2731
2867
  // A second copy of a preset keeps the number its instance name got: 评审官 → 评审官2.
2732
2868
  if (preset.label) label_drafts[name] = preset.label + name.slice(preset.name.length);
2733
2869
  // A workflow's card is built for that workflow alone and never updates a saved preset.
2734
- if (expert_presets().includes(preset)) preset_origins[name] = preset.name;
2735
- else delete preset_origins[name];
2870
+ const is_saved = !preset._from_workflow && (preset.scope === "project" || expert_presets().some(item => item.name === preset.name));
2871
+ if (is_saved) {
2872
+ preset_origins[name] = {
2873
+ name: preset.name,
2874
+ id: preset.id || "",
2875
+ scope: preset.scope || "global",
2876
+ project_id: preset.project_id || "",
2877
+ project_name: preset.project_name || "",
2878
+ readonly: Boolean(preset.readonly),
2879
+ requested_access: preset.requested_access || "",
2880
+ trusted: preset.trusted,
2881
+ skills: Array.isArray(preset.skills) ? [...preset.skills] : undefined,
2882
+ };
2883
+ } else delete preset_origins[name];
2736
2884
  publish_view();
2737
2885
  }
2738
2886
 
2739
- /** The saved preset a card was added from, or "" for a card of its own. */
2887
+ /** The saved preset name a card was added from, or "" for a card of its own. */
2740
2888
  function preset_origin(name) {
2741
- return preset_origins[name] || "";
2889
+ const origin = preset_origins[name];
2890
+ return typeof origin === "string" ? origin : origin?.name || "";
2891
+ }
2892
+
2893
+ /** Full origin metadata (`{ name, id, scope, project_id, project_name, readonly, requested_access, trusted, skills }`) or null. */
2894
+ function preset_origin_info(name) {
2895
+ const origin = preset_origins[name];
2896
+ if (!origin) return null;
2897
+ return typeof origin === "string" ? { name: origin, scope: "global", project_id: "", readonly: false } : origin;
2742
2898
  }
2743
2899
 
2744
2900
  /** Rename one card before the room or invitation is submitted; empty goes back to its default name. */
@@ -2760,7 +2916,7 @@ function member_label(name) {
2760
2916
  }
2761
2917
 
2762
2918
  /** The instance a preset of this platform is saved under for a free name: the name itself when it is already one, else platform-name. */
2763
- function preset_identity(name, label) {
2919
+ function preset_identity(name, label, pool = null) {
2764
2920
  const platform = platform_of(name), text = label.trim();
2765
2921
  // A name typed with the platform's nickname (Gemini-1) maps to the platform's ID (Antigravity-1).
2766
2922
  const nickname = default_name(platform);
@@ -2769,7 +2925,7 @@ function preset_identity(name, label) {
2769
2925
  // An ID keeps only English letters, digits and underscores; a Chinese name becomes the label of a numbered ID.
2770
2926
  const suffix = text.replace(/[^0-9A-Za-z_]/g, "").slice(0, 16);
2771
2927
  if (suffix && suffix !== platform) return `${platform}-${suffix}`;
2772
- const taken = new Set(expert_presets().map(preset => preset.name));
2928
+ const taken = new Set((pool || expert_presets()).map(preset => preset.name));
2773
2929
  let number = 1;
2774
2930
  while (taken.has(`${platform}-preset${number}`)) number++;
2775
2931
  return `${platform}-preset${number}`;
@@ -2783,34 +2939,89 @@ function add_preset_instance(container_id, preset, value) {
2783
2939
  return name;
2784
2940
  }
2785
2941
 
2786
- /** Save one card as the user's preset, under a new display label or, without one, updating the preset of its own name. */
2787
- async function save_expert_preset(name, label) {
2942
+ /** Save one card as a global or project preset, under a new display label or updating its own origin preset. */
2943
+ async function save_expert_preset(name, label, options = {}) {
2788
2944
  const profile = state.launch.profiles[name] || {};
2789
- const id = label === undefined ? preset_origins[name] || name : preset_identity(name, label);
2790
- const shown = label === undefined ? expert_presets().find(item => item.name === id)?.label || "" : label.trim();
2945
+ const origin = preset_origin_info(name);
2946
+ const scope = options.scope || (label === undefined ? origin?.scope : "") || "global";
2947
+ const project_id = scope === "project" ? (options.project_id ?? (label === undefined ? origin?.project_id : "") ?? "") : "";
2948
+ const room_id = options.room_id || "";
2949
+ const cwd = scope === "project" ? (options.cwd || "") : "";
2950
+ const pool = scope === "project"
2951
+ ? (room_id ? project_presets(room_id) : state.launch.project_presets).filter(item => !project_id || item.project_id === project_id)
2952
+ : expert_presets();
2953
+ const id = label === undefined ? origin?.name || name : preset_identity(name, label, pool);
2954
+ const shown = label === undefined ? (pool.find(item => item.name === id)?.label || label_drafts[name] || "") : label.trim();
2791
2955
  const preset = { name: id, ...shown && shown !== id ? { label: shown } : {}, description: description_draft(name).trim(), project_access: profile.project_access || "read" };
2792
2956
  // Model and effort are always kept, "" meaning the software's own default, so a card added from the preset never
2793
2957
  // takes whatever the platform's card was last set to.
2794
2958
  for (const field of ["model", "effort"]) preset[field] = profile[field] || "";
2795
2959
  if (Object.hasOwn(profile, "system_prompt") && profile.system_prompt !== "") preset.system_prompt = profile.system_prompt;
2796
2960
  try {
2797
- await save_presets({ presets: [...state.launch.presets.filter(item => item.name !== id), preset] });
2798
- show_toast(t('已存为预设「{value1}」', { value1: preset.label || id }));
2961
+ const payload = { action: "save", scope, ...(project_id ? { project_id } : {}), ...(room_id ? { room_id } : {}),
2962
+ ...(cwd ? { cwd } : {}), preset, overwrite: options.overwrite !== false };
2963
+ const result = await save_presets(payload, { room_id });
2964
+ const saved_list = scope === "project" ? (result?.project_presets || []) : (result?.presets || []);
2965
+ const saved = saved_list.find(item => item.name === id && (scope !== "project" || !project_id || item.project_id === project_id));
2966
+ preset_origins[name] = {
2967
+ name: saved?.name || id,
2968
+ id: saved?.id || origin?.id || "",
2969
+ scope,
2970
+ project_id: saved?.project_id || project_id,
2971
+ project_name: saved?.project_name || origin?.project_name || "",
2972
+ readonly: false,
2973
+ requested_access: "",
2974
+ trusted: true,
2975
+ skills: saved?.skills || origin?.skills,
2976
+ };
2977
+ if (scope === "project") {
2978
+ profile.preset_scope = "project";
2979
+ if (preset_origins[name].project_id) profile.preset_project_id = preset_origins[name].project_id;
2980
+ } else {
2981
+ profile.preset_scope = "global";
2982
+ delete profile.preset_project_id;
2983
+ }
2984
+ if (scope === "project" && room_id && state.room?.id === room_id) await reload_room_models().catch(() => {});
2985
+ publish_view();
2986
+ show_toast(scope === "project" ? t('已存为项目预设「{value1}」', { value1: preset.label || id }) : t('已存为预设「{value1}」', { value1: preset.label || id }));
2799
2987
  return true;
2800
2988
  } catch (error) { show_toast(t('预设未保存:{value1}', { value1: error.message }), true); return false; }
2801
2989
  }
2802
2990
 
2803
- /** Remove the preset of this name from the add row: the user's own one, and a built-in one of the same name with it. */
2804
- async function delete_expert_preset(name) {
2805
- const builtin = state.launch.builtin_presets.some(item => item.name === name);
2806
- const shown = expert_presets().find(item => item.name === name)?.label || name;
2991
+ /** Remove a global or project preset from the add row. Accepts a name string (global) or an options object. */
2992
+ async function delete_expert_preset(target, options = {}) {
2993
+ const spec = typeof target === "string" ? { name: target, ...options } : { ...target, ...options };
2994
+ const scope = spec.scope || "global";
2995
+ const project_id = scope === "project" ? (spec.project_id || "") : "";
2996
+ const room_id = spec.room_id || "";
2997
+ const cwd = scope === "project" ? (spec.cwd || "") : "";
2998
+ const list = scope === "project" ? (room_id ? project_presets(room_id) : state.launch.project_presets) : expert_presets();
2999
+ const matched = list.find(item => item.name === spec.name && (scope !== "project" || !project_id || item.project_id === project_id));
3000
+ const shown = spec.label || matched?.label || spec.name;
2807
3001
  try {
2808
- await save_presets({ presets: state.launch.presets.filter(item => item.name !== name),
2809
- ...builtin ? { hidden_builtins: [...state.launch.hidden_builtins, name] } : {} });
3002
+ const payload = { action: "delete", scope, ...(project_id ? { project_id } : {}), ...(room_id ? { room_id } : {}),
3003
+ ...(cwd ? { cwd } : {}), ...(spec.id || matched?.id ? { id: spec.id || matched?.id } : {}), name: spec.name };
3004
+ await save_presets(payload, { room_id });
3005
+ if (scope === "project" && room_id && state.room?.id === room_id) await reload_room_models().catch(() => {});
2810
3006
  show_toast(t('已删除预设「{value1}」', { value1: shown }));
2811
3007
  } catch (error) { show_toast(t('预设未删除:{value1}', { value1: error.message }), true); }
2812
3008
  }
2813
3009
 
3010
+ /** Record local trust for an elevated project expert preset and refresh its status. */
3011
+ async function trust_expert_preset({ id = "", name = "", card_name = "", project_id = "", room_id = "", cwd = "" } = {}) {
3012
+ const payload = { action: "trust", ...(project_id ? { project_id } : {}), ...(room_id ? { room_id } : {}),
3013
+ ...(cwd ? { cwd } : {}), ...(id ? { id } : {}), ...(name ? { name } : {}) };
3014
+ const result = await local_launch_request("presets", payload);
3015
+ if (card_name && preset_origins[card_name]) {
3016
+ preset_origins[card_name] = { ...preset_origins[card_name], trusted: true, requested_access: "" };
3017
+ }
3018
+ apply_presets_result(result, { room_id });
3019
+ if (room_id && state.room?.id === room_id) await reload_room_models().catch(() => {});
3020
+ else if (cwd || project_id) await load_project_presets({ cwd, extra_directories: state.launch.workspace?.extra_directories || [], project_id }).catch(() => {});
3021
+ publish_view();
3022
+ return result;
3023
+ }
3024
+
2814
3025
  /** The description a card currently shows: its own draft, else its platform's template. */
2815
3026
  function description_draft(name) {
2816
3027
  return description_drafts[name] ?? description_template(name);
@@ -3195,7 +3406,9 @@ async function finish_message(result, job) {
3195
3406
  ...(job.payload.attachment_start ? { attachment_start: job.payload.attachment_start } : {}), source: "user", just_sent: true };
3196
3407
  // The card draws `rendered_text`, which only render_messages prepares; a receipt shown before the transcript read
3197
3408
  // needs it too, or the card shows its header with an empty body.
3198
- sent_message.rendered_text = link_attachment_placeholders(render_room_markdown(sent_message.text), attachments);
3409
+ const inlined = new Set();
3410
+ sent_message.rendered_text = link_attachment_placeholders(render_room_markdown(sent_message.text), attachments, inlined);
3411
+ sent_message.inline_images = [...inlined];
3199
3412
  sent_message.rendered_summary = render_room_markdown(sent_message.summary || "");
3200
3413
  const members = predicted_recipients(job.payload, state.room, state.launch?.room_models);
3201
3414
  if (members.length) {
@@ -3335,6 +3548,7 @@ async function finish_taking_queued(item, room_id, taken) {
3335
3548
  * read leaves the message queued.
3336
3549
  */
3337
3550
  async function edit_queued(item) {
3551
+ if (item.relay_room) return;
3338
3552
  const room_id = state.room.id;
3339
3553
  const files = item.attachments.length ? await read_queued_files(item, room_id) : [];
3340
3554
  if (state.room?.id !== room_id) return;
@@ -3920,8 +4134,20 @@ function attachment_download_attributes(file) {
3920
4134
  /**
3921
4135
  * Turn `[图片 #n]` / `[文件 #n]` in a rendered message into a link to its n-th attachment: a preview for what the page
3922
4136
  * can show, a download for the rest. Text outside the attachment count stays as written.
4137
+ * When `inlined` is passed, each image's first reference also places that image in a two-column grid right after its
4138
+ * paragraph or list item (so mid-sentence references never split a line and adjacent screenshots sit side by side);
4139
+ * a paragraph holding only newly inlined images becomes that grid itself.
3923
4140
  */
3924
- function link_attachment_placeholders(html, files = []) {
4141
+ const INLINE_FLUSH_AFTER = /^<\/(?:p|h[1-6])>$/i;
4142
+ const INLINE_FLUSH_BEFORE = /^(?:<\/(?:li|td|th|blockquote|div|dd|dt)>|<(?:ul|ol|p|blockquote|pre|table|hr|div|h[1-6])(?:\s|>))/i;
4143
+ const PLACEHOLDER_PATTERN = /\[(图片|文件) #(\d{1,4}|[0-9a-f]{32})\]/g;
4144
+
4145
+ function inline_image_grid(items, show_badge) {
4146
+ const cards = items.map(({ file, number }) => attachment_image_markup(file, { inline: true, badge: show_badge ? `#${number}` : "" })).join("");
4147
+ return `<div class="attachment-inline-grid" data-count="${items.length}">${cards}</div>`;
4148
+ }
4149
+
4150
+ function link_attachment_placeholders(html, files = [], inlined = null) {
3925
4151
  // A share page made without its attachments says so, rather than showing a tag that looks like it should open.
3926
4152
  const omitted = (kind, number) => `<span class="attachment-placeholder is-omitted" title="${escape_html(t("分享时未包含附件"))}">${escape_html(kind === "图片"
3927
4153
  ? t("[图片 #{number} · 未包含在分享中]", { number }) : t("[文件 #{number} · 未包含在分享中]", { number }))}</span>`;
@@ -3930,18 +4156,79 @@ function link_attachment_placeholders(html, files = []) {
3930
4156
  // in the message, which shows as every placeholder fitting a place while not every one fits a number.
3931
4157
  const numbers = [...html.matchAll(/\[(?:图片|文件) #(\d{1,4})\]/g)].map(([, number]) => Number(number));
3932
4158
  const by_number = numbers.every(number => files.some(file => file.number === number)) || !numbers.every(number => number <= files.length);
3933
- // A member may name a file by the attachment ID its upload returned; it shows as the file's number.
3934
- return html.replace(/\[(图片|文件) #(\d{1,4}|[0-9a-f]{32})\]/g, (match, kind, reference) => {
4159
+ const show_badge = files.filter(file => file.content_type.startsWith("image/")).length > 1;
4160
+ const resolve_placeholder = (match, kind, reference, pending = null) => {
3935
4161
  const by_id = reference.length === 32;
3936
4162
  const file = by_id ? files.find(item => item.id === reference) : by_number ? files.find(item => item.number === Number(reference)) : files[Number(reference) - 1];
3937
4163
  const number = by_id ? file?.number ?? (files.indexOf(file) + 1) : reference;
3938
4164
  if (!file) return SHARE && !by_id ? omitted(kind, number) : match;
4165
+ if (pending && kind === "图片" && file.content_type.startsWith("image/") && !inlined.has(file.id)) {
4166
+ inlined.add(file.id);
4167
+ pending.push({ file, number });
4168
+ }
3939
4169
  const previewable = file.content_type.startsWith("image/") || file.content_type === "application/pdf" || is_text_attachment(file);
3940
4170
  // The stored `[图片 #n]` / `[文件 #n]` is protocol text; only the shown label follows the page language.
3941
4171
  const label = escape_html(kind === "图片" ? t("[图片 #{number}]", { number }) : t("[文件 #{number}]", { number }));
3942
4172
  return previewable ? `<button type="button" class="attachment-placeholder" ${attachment_preview_attributes(file)} title="${escape_html(file.file_name)}">${label}</button>`
3943
4173
  : `<a class="attachment-placeholder" ${attachment_download_attributes(file)} download title="${escape_html(t("下载 {name}", { name: file.file_name }))}">${label}</a>`;
3944
- });
4174
+ };
4175
+ if (!inlined) return html.replace(PLACEHOLDER_PATTERN, (match, kind, reference) => resolve_placeholder(match, kind, reference));
4176
+ const output = [];
4177
+ let pending = [], code_depth = 0, paragraph_start = -1, paragraph_only_images = false;
4178
+ for (const token of html.match(/<[^>]+>|[^<]+/g) || []) {
4179
+ if (token[0] === "<") {
4180
+ if (/^<(?:pre|code)(?:\s|>)/i.test(token)) code_depth += 1;
4181
+ else if (/^<\/(?:pre|code)>$/i.test(token)) code_depth = Math.max(0, code_depth - 1);
4182
+ if (code_depth === 0 && /^<p(?:\s|>)/i.test(token)) {
4183
+ if (pending.length) { output.push(inline_image_grid(pending, show_badge)); pending = []; }
4184
+ paragraph_start = output.length;
4185
+ paragraph_only_images = true;
4186
+ output.push(token);
4187
+ } else if (code_depth === 0 && INLINE_FLUSH_AFTER.test(token)) {
4188
+ if (pending.length && /^<\/p>$/i.test(token) && paragraph_start >= 0 && paragraph_only_images) {
4189
+ output.length = paragraph_start;
4190
+ output.push(inline_image_grid(pending, show_badge));
4191
+ } else {
4192
+ output.push(token);
4193
+ if (pending.length) output.push(inline_image_grid(pending, show_badge));
4194
+ }
4195
+ pending = [];
4196
+ paragraph_start = -1;
4197
+ paragraph_only_images = false;
4198
+ } else if (code_depth === 0 && INLINE_FLUSH_BEFORE.test(token)) {
4199
+ if (pending.length) { output.push(inline_image_grid(pending, show_badge)); pending = []; }
4200
+ paragraph_start = -1;
4201
+ paragraph_only_images = false;
4202
+ output.push(token);
4203
+ } else {
4204
+ if (paragraph_start >= 0 && !/^<br\s*\/?>$/i.test(token)) paragraph_only_images = false;
4205
+ output.push(token);
4206
+ }
4207
+ continue;
4208
+ }
4209
+ if (code_depth > 0) { output.push(token); continue; }
4210
+ let last_index = 0, built = "";
4211
+ PLACEHOLDER_PATTERN.lastIndex = 0;
4212
+ for (let match; (match = PLACEHOLDER_PATTERN.exec(token));) {
4213
+ const gap = token.slice(last_index, match.index);
4214
+ if (paragraph_only_images && gap.trim()) paragraph_only_images = false;
4215
+ const before = pending.length;
4216
+ const link = resolve_placeholder(match[0], match[1], match[2], pending);
4217
+ last_index = match.index + match[0].length;
4218
+ const punctuation = link !== match[0] && token.slice(last_index).match(/^[,。!?、;:,.!?;:]+/)?.[0];
4219
+ built += gap + (punctuation ? `<span class="attachment-reference-end">${link}${punctuation}</span>` : link);
4220
+ if (punctuation) {
4221
+ last_index += punctuation.length;
4222
+ paragraph_only_images = false;
4223
+ }
4224
+ if (paragraph_only_images && pending.length === before) paragraph_only_images = false;
4225
+ }
4226
+ const tail = token.slice(last_index);
4227
+ if (paragraph_only_images && tail.trim()) paragraph_only_images = false;
4228
+ output.push(built + tail);
4229
+ }
4230
+ if (pending.length) output.push(inline_image_grid(pending, show_badge));
4231
+ return output.join("");
3945
4232
  }
3946
4233
 
3947
4234
  // The largest box a message image shows in (frontend/markdown.css `.attachment-image img`).
@@ -3956,10 +4243,21 @@ function attachment_image_style(file) {
3956
4243
  const width = Number(file.width), height = Number(file.height);
3957
4244
  if (!(width > 0 && height > 0)) return "";
3958
4245
  const shown = Math.max(1, Math.floor(Math.min(width, ATTACHMENT_IMAGE_MAX_WIDTH, ATTACHMENT_IMAGE_MAX_HEIGHT * width / height)));
3959
- return ` style="--image-width: ${shown}px; --image-ratio: ${width} / ${height}"`;
4246
+ return ` style="--image-width: ${shown}px; --image-natural-width: ${width}px; --image-ratio: ${width} / ${height}; --image-ratio-num: ${(width / height).toFixed(4)}"`;
3960
4247
  }
3961
4248
 
3962
4249
  /** Render immutable file cards shared by messages, original-message dialogs, and themes. */
4250
+ /** A message image as its preview button, shown in the list or where the answer refers to it. */
4251
+ function attachment_image_markup(file, { inline = false, badge = "" } = {}) {
4252
+ const url = `/api/rooms/${encodeURIComponent(file.room_id)}/attachments/${encodeURIComponent(file.id)}/content`;
4253
+ const local_preview = relay_files.get(url);
4254
+ const source = typeof local_preview === "string" ? `src="${escape_html(local_preview)}"` : files_by_blob() ? `data-relay-src="${url}"` : `src="${url}"`;
4255
+ const inline_attr = inline ? ` data-inline-image="${escape_html(file.id)}"` : "";
4256
+ const badge_attr = badge ? ` data-image-badge="${escape_html(badge)}"` : "";
4257
+ return `<button type="button" class="attachment-image" ${attachment_preview_attributes(file)}${inline_attr}${badge_attr}${attachment_image_style(file)}>
4258
+ <img ${source} alt="${escape_html(file.file_name)}" loading="lazy"></button>`;
4259
+ }
4260
+
3963
4261
  function attachment_markup(files = []) {
3964
4262
  if (!files.length) return "";
3965
4263
  return `<div class="message-attachments">${files.map(file => {
@@ -3970,14 +4268,15 @@ function attachment_markup(files = []) {
3970
4268
  const local_preview = file.content_type.startsWith("image/") && relay_files.get(url);
3971
4269
  const source = typeof local_preview === "string" ? `src="${escape_html(local_preview)}"` : files_by_blob() ? `data-relay-src="${url}"` : `src="${url}"`;
3972
4270
  const download = attachment_download_attributes(file);
3973
- if (file.content_type.startsWith("image/")) return `<button type="button" class="attachment-image" ${preview_attributes}${attachment_image_style(file)}>
3974
- <img ${source} alt="${name}" loading="lazy"></button>`;
4271
+ if (file.content_type.startsWith("image/")) return attachment_image_markup(file);
3975
4272
  // Audio and video play in place with the browser's own controls; a format it cannot decode still has its download.
3976
4273
  if (/^(audio|video)\//.test(file.content_type)) {
3977
4274
  const tag = file.content_type.startsWith("video/") ? "video" : "audio";
3978
4275
  // The Vue workspace registers the Video.js players (Chinese labels, speed, full screen); the classic page has none.
3979
4276
  const skinned = Boolean(customElements.get(`${tag}-player`));
3980
- const media = `<${tag} ${source} ${skinned ? "" : "controls "}preload="metadata" playsinline aria-label="${name}"></${tag}>`;
4277
+ // A transparent poster lets the themed surface show before the browser decodes the first frame.
4278
+ const poster = tag === "video" ? 'poster="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" ' : "";
4279
+ const media = `<${tag} ${source} ${poster}${skinned ? "" : "controls "}preload="metadata" playsinline aria-label="${name}"></${tag}>`;
3981
4280
  return `<div class="attachment-media attachment-${tag}">${skinned ? `<${tag}-player><${tag}-skin class="attachment-player">${media}</${tag}-skin></${tag}-player>` : media}
3982
4281
  <span class="attachment-media-failed">${escape_html(t("浏览器无法播放这个文件的格式,请点下面的文件名下载后用本机软件打开。"))}</span>
3983
4282
  <a class="attachment-media-name" ${download} download title="${escape_html(t("下载 {name}", { name: file.file_name }))}">${name}<small>${attachment_size(file.size)}</small></a></div>`;
@@ -4530,7 +4829,7 @@ async function local_launch_request(action, payload) {
4530
4829
  catch { throw new Error(t('本机服务返回了无法识别的内容(HTTP {status}):{excerpt}', { status: response.status, excerpt: raw.replace(/<[^>]*>/g, " ").replace(/\s+/g, " ").trim().slice(0, 80) })); }
4531
4830
  // `code` names a refusal the page acts on (e.g. a workflow changed since it was loaded); the text alone is for people.
4532
4831
  // `files` and `spots` list what a website deploy refused (runner/site_deploy.mjs).
4533
- if (!response.ok) throw Object.assign(new Error(server_text(result.error_text, result.error) || t('本机启动请求失败')), { status: response.status, launch: result.launch, code: result.code, files: result.files, spots: result.spots });
4832
+ if (!response.ok) throw Object.assign(new Error(server_text(result.error_text, result.error) || t('本机启动请求失败')), { status: response.status, launch: result.launch, code: result.code, files: result.files, spots: result.spots, untrusted_reasons: result.untrusted_reasons });
4534
4833
  return result;
4535
4834
  }
4536
4835
 
@@ -4924,7 +5223,7 @@ async function relay_command_once(action, payload) {
4924
5223
  try { answer = await relay_exchange(action, payload, limit); }
4925
5224
  catch (error) { if (computer_rooms_only() || (error.status !== 404 && !error.offline)) throw error; }
4926
5225
  const { status, body } = answer ?? await queued_relay_command(action, payload, limit);
4927
- if (status >= 400) throw Object.assign(new Error(server_text(body.error_text, body.error) || t('本机操作失败')), { status, launch: body.launch, need: body.need, room_id: body.room_id, code: body.code });
5226
+ if (status >= 400) throw Object.assign(new Error(server_text(body.error_text, body.error) || t('本机操作失败')), { status, launch: body.launch, need: body.need, room_id: body.room_id, code: body.code, untrusted_reasons: body.untrusted_reasons });
4928
5227
  return body;
4929
5228
  }
4930
5229
 
@@ -5217,6 +5516,9 @@ async function show_computer_rooms(remote) {
5217
5516
  state.remote_rooms = Boolean(remote);
5218
5517
  // The two lists share no rooms, so nothing read from one may be shown for the other.
5219
5518
  room_views.clear();
5519
+ recent_room_models.clear();
5520
+ preloaded_room_models.clear();
5521
+ state.launch.room_models = null;
5220
5522
  message_histories.clear();
5221
5523
  history_cards.clear();
5222
5524
  reset_background_reads();
@@ -5413,6 +5715,8 @@ function discard_launch(id) {
5413
5715
  */
5414
5716
  async function load_launch_settings({ relay_known = () => {} } = {}) {
5415
5717
  const local = state.admin.local || ["127.0.0.1", "localhost"].includes(location.hostname);
5718
+ recent_room_models.clear();
5719
+ preloaded_room_models.clear();
5416
5720
  state.launch.room_models = null;
5417
5721
  state.launch.model_catalogs = {};
5418
5722
  state.launch.connect_command = local ? "codiscuss local open" : `codiscuss local connect "${location.origin}"`;
@@ -5442,7 +5746,7 @@ async function load_launch_settings({ relay_known = () => {} } = {}) {
5442
5746
  state.launch.saved_profiles = JSON.parse(JSON.stringify(settings.participants || {}));
5443
5747
  state.launch.create_preferences = { ...settings.create_preferences, ...create_preferences_pending };
5444
5748
  Object.assign(state.launch, { available: true, profiles: settings.participants, projects: settings.projects || [], projects_restricted: settings.projects_restricted === true, user_home: settings.user_home || "", api_providers: settings.api_providers || {}, api_keys: settings.api_keys || {}, managed_api_keys: settings.managed_api_keys || [],
5445
- presets: settings.presets || [], builtin_presets: settings.builtin_presets || [], hidden_builtins: settings.hidden_builtins || [], skilled_presets: settings.skilled_presets || [], workflows: settings.workflows || [], card_platforms: settings.platforms || [], description_templates: settings.description_templates || {},
5749
+ presets: (settings.presets || []).map(item => ({ scope: "global", ...item })), builtin_presets: settings.builtin_presets || [], hidden_builtins: settings.hidden_builtins || [], skilled_presets: settings.skilled_presets || [], skilled_project_presets: settings.skilled_project_presets || [], workflows: (settings.workflows || []).map(item => ({ scope: "global", ...item })), card_platforms: settings.platforms || [], description_templates: settings.description_templates || {},
5446
5750
  scheduler_providers: settings.scheduler_providers || {}, invite_site: settings.invite_site || null, error: "",
5447
5751
  notice: relay_machine ? t('经电脑「{value1}」执行本机操作', { value1: relay_machine.name }) : local_connection ? t('已连接本机服务,讨论保存在当前网站') : "" });
5448
5752
  Object.values(state.launch.profiles).forEach(fill_api_key);
@@ -5450,6 +5754,7 @@ async function load_launch_settings({ relay_known = () => {} } = {}) {
5450
5754
  apply_create_preferences();
5451
5755
  flush_create_preferences();
5452
5756
  load_room_models();
5757
+ load_storage();
5453
5758
  } catch (error) {
5454
5759
  // An unpaired or expired device keeps its way to the computer: pairing and renewal go through it.
5455
5760
  // A website without rooms of its own reaches the computer only through the relay, so one failed request keeps it.
@@ -5521,9 +5826,16 @@ let members_seen = null;
5521
5826
  /** Read saved choices for the active room without using drafts or delaying discussion refreshes. */
5522
5827
  /** The parts of the computer's room-models answer the page keeps. */
5523
5828
  function room_models_fields(result) {
5829
+ const extra_directory_entries = result.extra_directories || [];
5524
5830
  return { participants: result.participants, registered: result.registered,
5525
- scheduler: result.scheduler || null, project_directory: result.project_directory || "", extra_directories: result.extra_directories || [],
5526
- workflow: result.workflow || null, host_workflows: Boolean(result.host_workflows), host_permissions: result.host_permissions || null, api_max_requests: result.api_max_requests,
5831
+ scheduler: result.scheduler || null, project_directory: result.project_directory || "",
5832
+ extra_directory_entries, extra_directories: extra_directory_entries.map(extra_directory_path),
5833
+ workflow: result.workflow || null,
5834
+ project_workflows: (result.project_workflows || []).map(item => ({ scope: "project", ...item })),
5835
+ project_experts: (result.project_experts || []).map(item => ({ scope: "project", ...item })),
5836
+ project_roots: result.project_roots || [],
5837
+ host_workflows: Boolean(result.host_workflows), host_permissions: result.host_permissions || null, api_max_requests: result.api_max_requests,
5838
+ draft_key: result.draft_key || "",
5527
5839
  image_generation: Boolean(result.image_generation), image_configured: Boolean(result.image_configured) };
5528
5840
  }
5529
5841
 
@@ -5540,18 +5852,29 @@ async function load_room_models(force = false) {
5540
5852
  && (previous.loading || previous.participants)) return;
5541
5853
  // The last answer stays on screen while the new one is read.
5542
5854
  const same_room = previous?.room_id === room.id;
5543
- const current = { participants: null, project_directory: "", extra_directories: [], ...(same_room ? previous : {}), room_id: room.id, revision, loading: true, error: "" };
5855
+ const current = { participants: null, project_directory: "", extra_directories: [], project_workflows: [], project_experts: [], project_roots: [], ...(same_room ? previous : {}), room_id: room.id, revision, loading: true, error: "" };
5544
5856
  const preloaded = preloaded_room_models.get(room.id);
5545
5857
  preloaded_room_models.delete(room.id);
5546
5858
  if (preloaded) Object.assign(current, room_models_fields(preloaded), { loading: false });
5547
5859
  state.launch.room_models = current;
5860
+ state.launch.project_workflows = current.project_workflows || [];
5861
+ state.launch.project_roots = current.project_roots || [];
5548
5862
  publish_view();
5549
5863
  const live = () => state.launch.room_models === current && state.room?.id === room.id;
5550
5864
  // agy is run to name its default model, which takes seconds; everything else is shown first and agy follows.
5551
5865
  try {
5552
5866
  const result = preloaded || await local_launch_request("room-models", { room_id: room.id, quick: true });
5553
- if (live() && result.room_id === room.id) Object.assign(current, room_models_fields(result));
5554
5867
  if (live() && result.room_id === room.id) {
5868
+ for (const [name, profile] of Object.entries(result.participants || {})) {
5869
+ const prior = current.participants?.[name];
5870
+ if (profile.defaults_pending && prior?.adapter === profile.adapter && prior.default_model) {
5871
+ profile.default_model = prior.default_model;
5872
+ profile.default_effort = prior.default_effort;
5873
+ }
5874
+ }
5875
+ Object.assign(current, room_models_fields(result), { read_at: Date.now() });
5876
+ state.launch.project_workflows = current.project_workflows || [];
5877
+ state.launch.project_roots = current.project_roots || [];
5555
5878
  // Compared with the last answer for this room, which a reload clears from the state but not from here.
5556
5879
  if (members_seen?.room_id === room.id) warn_outside_members(members_seen.participants, result.participants);
5557
5880
  members_seen = { room_id: room.id, participants: result.participants };
@@ -5576,9 +5899,116 @@ async function load_room_models(force = false) {
5576
5899
 
5577
5900
  /** Read this computer's saved choices again, as after a failed read. */
5578
5901
  function reload_room_models() {
5902
+ load_storage();
5579
5903
  return load_room_models(true);
5580
5904
  }
5581
5905
 
5906
+ const STORAGE_FRESH_MS = 30000;
5907
+ const STORAGE_GIB = 1024 ** 3;
5908
+ const STORAGE_MIB = 1024 ** 2;
5909
+ const STORAGE_KIB = 1024;
5910
+ let storage_request_seq = 0;
5911
+ let storage_warn_announced = false;
5912
+ const storage_cleaning_keys = new Set();
5913
+
5914
+ function format_storage_size(bytes) {
5915
+ const safe = Math.max(0, Number(bytes) || 0);
5916
+ for (const [unit, label] of [[STORAGE_GIB, "GiB"], [STORAGE_MIB, "MiB"], [STORAGE_KIB, "KiB"]]) {
5917
+ if (safe >= unit) {
5918
+ const value = safe / unit;
5919
+ return `${Number.isInteger(value) ? value : value.toFixed(2).replace(/\.?0+$/, "")} ${label}`;
5920
+ }
5921
+ }
5922
+ return `${Math.round(safe)} B`;
5923
+ }
5924
+
5925
+ function apply_storage_snapshot(result) {
5926
+ state.launch.storage = result;
5927
+ state.launch.storage_read_at = Date.now();
5928
+ state.launch.storage_error = "";
5929
+ const limits = result?.limits || result?.thresholds || {};
5930
+ const warn_bytes = Number(limits.warn_bytes ?? limits.home_warn_bytes ?? limits.home_warn ?? result?.home_warn) || 8 * STORAGE_GIB;
5931
+ const limit_bytes = Number(limits.home_bytes ?? limits.home_limit_bytes ?? limits.home_limit ?? result?.home_limit) || 10 * STORAGE_GIB;
5932
+ const total_bytes = Number(result?.total_bytes || 0);
5933
+ const warning = Boolean(result?.warning || total_bytes >= warn_bytes);
5934
+ if (!warning) { storage_warn_announced = false; return; }
5935
+ if (storage_warn_announced) return;
5936
+ storage_warn_announced = true;
5937
+ notify("warning", result?.warning_reason || t("本机 .codiscuss 数据已占 {used}(不含语音模型),接近 {limit} 上限,请在房间外的 AI 对话中运行 $codiscuss-draft-cleanup 或清理临时文件。",
5938
+ { used: format_storage_size(total_bytes), limit: format_storage_size(limit_bytes) }));
5939
+ }
5940
+
5941
+ /** Read local or paired-computer storage usage without blocking room actions; late answers are ignored. */
5942
+ async function load_storage(force = false) {
5943
+ if (SHARE || !state.launch.available) return null;
5944
+ if (!force && state.launch.storage && Date.now() - (state.launch.storage_read_at || 0) < STORAGE_FRESH_MS) return state.launch.storage;
5945
+ const seq = ++storage_request_seq;
5946
+ state.launch.storage_loading = true;
5947
+ publish_view();
5948
+ try {
5949
+ const result = await local_launch_request("storage");
5950
+ if (seq !== storage_request_seq) return null;
5951
+ apply_storage_snapshot(result);
5952
+ return result;
5953
+ } catch (error) {
5954
+ if (seq === storage_request_seq) state.launch.storage_error = error.message || "";
5955
+ return null;
5956
+ } finally {
5957
+ if (seq === storage_request_seq) {
5958
+ state.launch.storage_loading = false;
5959
+ publish_view();
5960
+ }
5961
+ }
5962
+ }
5963
+
5964
+ /** Clean finished execution temp files on the local or paired computer, refreshing the snapshot afterwards. */
5965
+ async function clean_storage(target = {}) {
5966
+ if (SHARE || !state.launch.available) return false;
5967
+ const payload = target && typeof target === "object"
5968
+ ? Object.fromEntries(Object.entries(target).filter(([, value]) => Boolean(value)))
5969
+ : {};
5970
+ const key = payload.room_id || payload.room_key || "__all__";
5971
+ if (storage_cleaning_keys.has(key)) return false;
5972
+ storage_cleaning_keys.add(key);
5973
+ state.launch.storage_cleaning = [...storage_cleaning_keys];
5974
+ publish_view();
5975
+ try {
5976
+ const result = await local_launch_request("storage-clean", payload);
5977
+ const freed = Number(result?.freed_bytes ?? result?.removed_bytes ?? 0) || 0;
5978
+ const removed = Number(result?.removed_dirs ?? result?.removed ?? result?.cleaned ?? 0) || 0;
5979
+ const skipped = Number(result?.skipped ?? result?.failed ?? 0) || 0;
5980
+ if (result?.storage) {
5981
+ storage_request_seq += 1;
5982
+ apply_storage_snapshot(result.storage);
5983
+ } else {
5984
+ await load_storage(true);
5985
+ }
5986
+ if (removed > 0 || freed > 0) {
5987
+ if (freed > 0) {
5988
+ notify(skipped ? "warning" : "info", skipped
5989
+ ? t("已清理 {count} 个临时目录,释放 {size};另有 {skipped} 项暂无法清理", { count: removed, size: format_storage_size(freed), skipped })
5990
+ : t("已清理 {count} 个临时目录,释放 {size}", { count: removed, size: format_storage_size(freed) }));
5991
+ } else {
5992
+ notify(skipped ? "warning" : "info", skipped
5993
+ ? t("已清理 {count} 个临时目录;另有 {skipped} 项暂无法清理", { count: removed, skipped })
5994
+ : t("已清理 {count} 个临时目录", { count: removed }));
5995
+ }
5996
+ } else if (skipped > 0) {
5997
+ notify("warning", t("没有可立即清理的已结束临时目录;有 {skipped} 项暂无法清理", { skipped }));
5998
+ } else {
5999
+ notify("info", t("没有可清理的已结束执行临时文件"));
6000
+ }
6001
+ return true;
6002
+ } catch (error) {
6003
+ notify("error", error.message);
6004
+ return false;
6005
+ } finally {
6006
+ storage_cleaning_keys.delete(key);
6007
+ state.launch.storage_cleaning = [...storage_cleaning_keys];
6008
+ publish_view();
6009
+ }
6010
+ }
6011
+
5582
6012
  /** Read a directory or file from the room's saved project through the authenticated local connection. */
5583
6013
  function read_room_files(room_id, path = "", offset = 0, query = "", root = 0, folders = null) {
5584
6014
  return local_launch_request("room-files", { room_id, path, offset, ...(query ? { query } : { root }), ...(folders ? { folders } : {}), token: localStorage.getItem(`discuss-access:${room_id}`) });
@@ -5777,7 +6207,7 @@ function participant_model(name, room, saved, brief = false) {
5777
6207
  const profile = saved?.room_id === room.id ? saved.participants?.[name] : null;
5778
6208
  if (!profile) return "";
5779
6209
  // Only an agy member without a chosen model depends on the default that is read later.
5780
- if (!profile.model && !profile.actual_model && profile.defaults_pending) return t('读取中…');
6210
+ if (!profile.model && !profile.actual_model && !profile.default_model && profile.defaults_pending) return t('读取中…');
5781
6211
  // App members choose in their own chat, so only their session log knows.
5782
6212
  const app = ["codex", "antigravity"].includes(profile.adapter);
5783
6213
  // What the session last actually ran with comes first, so a member that says or is set to another model cannot mislead;
@@ -6072,7 +6502,7 @@ function restore_launch_profile(name, profile) {
6072
6502
  function launch_options() {
6073
6503
  const { local_project, extra_directories, ...workspace } = state.launch.workspace;
6074
6504
  // Extra project directories go with a main one only, and rows left blank are dropped.
6075
- const extras = workspace.cwd ? (extra_directories || []).map(path => path.trim()).filter(Boolean) : [];
6505
+ const extras = workspace.cwd ? normalized_extra_directories(extra_directories) : [];
6076
6506
  // The paired computer resolves a project id to its own folder; a browser with the local service sends the folder itself.
6077
6507
  return JSON.parse(JSON.stringify({ participants: state.launch.profiles, ...workspace, ...(extras.length ? { extra_directories: extras } : {}),
6078
6508
  ...(!state.launch.available && local_project ? { local_project } : {}), entry: "web" }));
@@ -6133,15 +6563,29 @@ async function set_room_project_directory(cwd) {
6133
6563
  try { await local_launch_request("room-settings", { room_id, token, cwd }); }
6134
6564
  catch (error) { notify("error", error.message); throw error; }
6135
6565
  await reload_room_models();
6566
+ reload_workflows().catch(() => {});
6567
+ }
6568
+
6569
+ function extra_directory_path(item) {
6570
+ return typeof item === "string" ? item : item.path;
6571
+ }
6572
+
6573
+ function normalized_extra_directories(directories = []) {
6574
+ return directories.flatMap((item) => {
6575
+ const path = extra_directory_path(item).trim();
6576
+ if (!path) return [];
6577
+ return [typeof item === "string" ? path : { ...item, path }];
6578
+ });
6136
6579
  }
6137
6580
 
6138
6581
  /** Replace this room's extra project directories (the main one never changes); applies from each member's next execution. */
6139
6582
  async function set_room_extra_directories(directories) {
6140
6583
  const room_id = state.room.id;
6141
6584
  const token = localStorage.getItem(`discuss-access:${room_id}`) || "";
6142
- try { await local_launch_request("room-settings", { room_id, token, extra_directories: directories }); }
6585
+ try { await local_launch_request("room-settings", { room_id, token, extra_directories: normalized_extra_directories(directories) }); }
6143
6586
  catch (error) { notify("error", error.message); throw error; }
6144
6587
  await reload_room_models();
6588
+ reload_workflows().catch(() => {});
6145
6589
  }
6146
6590
 
6147
6591
  /** Change how many model requests one execution of this room's API members may make; applies from the next one. */
@@ -6207,10 +6651,21 @@ async function set_room_host_workflows({ room_id, permissions }) {
6207
6651
 
6208
6652
  // Workflows: a host's SKILL.md plus agent cards, kept on this computer and enabled per room.
6209
6653
 
6210
- /** Read the workflow library again after it changed. */
6211
- async function reload_workflows() {
6212
- const result = await local_launch_request("workflows", { action: "list" });
6213
- state.launch.workflows = result.workflows || [];
6654
+ /** Read the global and current room's project workflow lists again after they changed. */
6655
+ async function reload_workflows(options = {}) {
6656
+ const room_id = options.room_id !== undefined ? options.room_id : (state.room?.id || "");
6657
+ const payload = { action: "list", ...(room_id ? { room_id } : {}), ...(options.project_id ? { project_id: options.project_id } : {}),
6658
+ ...(options.cwd ? { cwd: options.cwd } : {}), ...(options.extra_directories?.length ? { extra_directories: options.extra_directories } : {}) };
6659
+ const result = await local_launch_request("workflows", payload);
6660
+ state.launch.workflows = (result.workflows || []).map(item => ({ scope: "global", ...item }));
6661
+ if (!room_id || state.room?.id === room_id) {
6662
+ state.launch.project_workflows = (result.project_workflows || []).map(item => ({ scope: "project", ...item }));
6663
+ state.launch.project_roots = result.project_roots || [];
6664
+ if (room_id && state.launch.room_models?.room_id === room_id) {
6665
+ state.launch.room_models.project_workflows = state.launch.project_workflows;
6666
+ state.launch.room_models.project_roots = state.launch.project_roots;
6667
+ }
6668
+ }
6214
6669
  // The platforms cards may name on that computer; a card naming another cannot join until its platform changes.
6215
6670
  state.launch.card_platforms = result.platforms || [];
6216
6671
  publish_view();
@@ -6219,16 +6674,61 @@ async function reload_workflows() {
6219
6674
 
6220
6675
  /** A workflow card as an expert preset: the card ID is only the workflow's own handle. */
6221
6676
  function workflow_preset({ card, requested_access, needs_platform, ...preset }) {
6222
- return preset;
6677
+ return { ...preset, _from_workflow: true };
6223
6678
  }
6224
6679
 
6225
6680
  /** Bind a workflow to this room after its cards were invited (or brought back); the host reads it from the next task. */
6226
- async function enable_room_workflow({ id, members }) {
6681
+ async function enable_room_workflow({ id, scope = "", project_id = "", members, trust = false, label = "", project_name = "" }) {
6227
6682
  const room_id = state.room.id;
6228
6683
  const token = localStorage.getItem(`discuss-access:${room_id}`) || "";
6229
- await local_launch_request("room-workflow", { room_id, token, action: "enable", workflow: { id, members } });
6684
+ const wf = { id, ...(scope ? { scope } : {}), ...(project_id ? { project_id } : {}), members };
6685
+ try {
6686
+ await local_launch_request("room-workflow", { room_id, token, action: "enable", workflow: wf, ...(trust ? { trust: true } : {}) });
6687
+ } catch (error) {
6688
+ if (error.code === "workflow_untrusted") {
6689
+ const matched = (state.launch.project_workflows || []).find(item => item.id === id && (!project_id || item.project_id === project_id));
6690
+ state.launch.workflow_trust_prompt = {
6691
+ room_id, id, scope: scope || "project", project_id: project_id || matched?.project_id || "",
6692
+ label: label || matched?.label || id, project_name: project_name || matched?.project_name || "",
6693
+ members, untrusted_reasons: error.untrusted_reasons || matched?.untrusted_reasons || {}, error: error.message,
6694
+ };
6695
+ publish_view();
6696
+ error.notified = true;
6697
+ }
6698
+ throw error;
6699
+ }
6700
+ state.launch.workflow_trust_prompt = null;
6230
6701
  notify("info", t('工作流已启用,主持人下一次任务起按它组织工作'));
6231
6702
  await reload_room_models();
6703
+ reload_workflows().catch(() => {});
6704
+ }
6705
+
6706
+ /** Trust a project workflow on this computer and refresh the workflow lists. */
6707
+ async function trust_project_workflow({ id, project_id = "", room_id = "", cwd = "" }) {
6708
+ const target_room = room_id || state.room?.id || "";
6709
+ await local_launch_request("workflows", { action: "trust", id, ...(project_id ? { project_id } : {}), ...(target_room ? { room_id: target_room } : {}), ...(cwd ? { cwd } : {}) });
6710
+ await reload_workflows();
6711
+ if (target_room && state.room?.id === target_room) await reload_room_models();
6712
+ }
6713
+
6714
+ /** Confirm the pending untrusted workflow prompt by enabling it with `trust: true`. */
6715
+ async function confirm_workflow_trust() {
6716
+ const prompt = state.launch.workflow_trust_prompt;
6717
+ if (!prompt) return false;
6718
+ try {
6719
+ await enable_room_workflow({ id: prompt.id, scope: prompt.scope, project_id: prompt.project_id, members: prompt.members, trust: true, label: prompt.label, project_name: prompt.project_name });
6720
+ return true;
6721
+ } catch (error) {
6722
+ if (!error.notified) notify("error", error.message);
6723
+ return false;
6724
+ }
6725
+ }
6726
+
6727
+ /** Dismiss the pending untrusted workflow confirmation prompt. */
6728
+ function dismiss_workflow_trust() {
6729
+ if (!state.launch.workflow_trust_prompt) return;
6730
+ state.launch.workflow_trust_prompt = null;
6731
+ publish_view();
6232
6732
  }
6233
6733
 
6234
6734
  /**
@@ -6926,7 +7426,7 @@ async function retract_latest() {
6926
7426
  try { await last.done; } catch { return; }
6927
7427
  if (state.room?.id !== room_id) return;
6928
7428
  }
6929
- const message = state.messages.findLast(item => item.author === "用户" && !item.withdrawn);
7429
+ const message = state.messages.findLast(item => item.author === "用户" && !item.relay_room && !item.withdrawn);
6930
7430
  if (message) await retract_message(message.id);
6931
7431
  }
6932
7432
 
@@ -7391,6 +7891,8 @@ function update_directory_drag(event) {
7391
7891
  if (state.directory_sort === "recent") return;
7392
7892
  const target = hit.closest("[data-drag-room]");
7393
7893
  if (!target || target.dataset.dragRoom === drag.id) return;
7894
+ const rooms = visible_rooms();
7895
+ if (directory_parent(rooms.find(room => room.id === drag.id), rooms) !== directory_parent(rooms.find(room => room.id === target.dataset.dragRoom), rooms)) return;
7394
7896
  const rect = target.getBoundingClientRect();
7395
7897
  const after = event.clientY > rect.top + rect.height / 2;
7396
7898
  drag.target = { action: "move", id: target.dataset.dragRoom, after };
@@ -7792,7 +8294,7 @@ function view_snapshot() {
7792
8294
  kinds: share_draft.files ? share_file_kinds(share_draft) : [], carried: share_carried_files(share_draft, false).reduce((total, file) => total + file.size, 0),
7793
8295
  carried_count: share_carried_files(share_draft, false).length,
7794
8296
  site_left_out: (share_draft.files || []).filter(file => !file.site_type).map(file => file.file_name) },
7795
- days: share_draft.days || SHARE_DEFAULT_DAYS, linked: Boolean(share_draft.linked || share_link(share_draft.room_id)), link: share_draft.link || null, cover_images: share_draft.cover_images || [], upload: share_draft.upload ? { ...share_draft.upload } : null } : null,
8297
+ days: share_draft.days || SHARE_DEFAULT_DAYS, linked: Boolean(share_draft.linked || share_link(share_draft.room_id)), link: share_draft.link || null, cover_images: share_draft.cover_images || [], sites: share_draft.sites || [], card_defaults: share_draft.card_defaults || null, upload: share_draft.upload ? { ...share_draft.upload } : null } : null,
7796
8298
  share_links: SHARE ? {} : share_links(), share_days: SHARE_DAYS,
7797
8299
  tab: state.tab, snapshot_id: state.snapshot_id, context_dirty: state.context_dirty,
7798
8300
  theme: document.documentElement.dataset.theme, fields, experts, launch: shown_launch(), named_followup: state.named_followup, create_discussion: state.create_discussion, create_goal: state.create_goal, create_chain_rounds: state.create_chain_rounds, create_host_workflows: state.create_host_workflows, create_host_permissions: state.create_host_permissions, create_api_max_requests: state.create_api_max_requests, create_auto_destroy: state.create_auto_destroy || 0, create_relay_rounds: state.create_relay_rounds ?? 0, create_image_generation: state.create_image_generation };
@@ -7897,6 +8399,9 @@ function preview_clicked_attachment(event) {
7897
8399
  function watch_room_files() {
7898
8400
  document.addEventListener("click", download_relay_file, true);
7899
8401
  document.addEventListener("error", mark_failed_media, true);
8402
+ document.addEventListener("loadeddata", event => {
8403
+ if (event.target.matches?.(".attachment-video video")) event.target.removeAttribute("poster");
8404
+ }, true);
7900
8405
  new MutationObserver((records) => { if (files_by_blob()) show_relay_images(records); }).observe(document.body, { childList: true, subtree: true });
7901
8406
  }
7902
8407
 
@@ -8306,14 +8811,15 @@ async function open_share_card(room_id, fallback) {
8306
8811
  share_draft = loading;
8307
8812
  publish_view();
8308
8813
  try {
8309
- await Promise.allSettled(["question", "outcome", "cover"].map(field => share_card_writes.get(room_id + "/" + field)));
8814
+ await Promise.allSettled(["question", "outcome", "cover", "copy"].map(field => share_card_writes.get(room_id + "/" + field)));
8310
8815
  const saved = await request_json(`/api/rooms/${encodeURIComponent(room_id)}/share-card`);
8311
8816
  if (share_draft !== loading) return;
8312
8817
  const job = shown_share_jobs().find(item => item.result?.url === saved.url);
8313
8818
  const previous = fallback?.url === saved.url ? fallback : job?.result;
8314
- const card = { title, members: [], stats: "", question: "", outcome: "", ...previous?.card, ...saved.card };
8819
+ const card = { title, members: [], stats: "", question: "", outcome: "", copy: "", ...previous?.card, ...saved.card };
8315
8820
  const link = { ...previous, url: saved.url, expires_at: saved.expires_at, share_id: saved.share_id, card };
8316
- share_draft = { room_id, title: card.title, phase: "published", link, cover_images: saved.images };
8821
+ share_draft = { room_id, title: card.title, phase: "published", link, cover_images: saved.images,
8822
+ sites: saved.sites || [], card_defaults: saved.defaults || null };
8317
8823
  } catch (error) {
8318
8824
  if (share_draft === loading) { share_draft = null; notify("error", error.message); }
8319
8825
  } finally { publish_view(); }
@@ -8327,15 +8833,16 @@ async function edit_share_card({ field, value, room_id, share_id }) {
8327
8833
  const key = room_id + "/" + field;
8328
8834
  const prior = share_card_writes.get(key);
8329
8835
  draft.saved_card ||= { ...card };
8330
- draft.link = { ...draft.link, card: { ...card, [field]: value } };
8836
+ const shown = value === null ? (field === "copy" ? "" : (draft.card_defaults?.[field] ?? "")) : value;
8837
+ draft.link = { ...draft.link, card: { ...card, [field]: shown } };
8331
8838
  const versions = draft.card_versions ||= {};
8332
8839
  const version = versions[field] = (versions[field] || 0) + 1;
8333
8840
  publish_view();
8334
- const delay = field === "cover" ? undefined : share_card_text_delay(draft, field);
8841
+ const delay = (field === "cover" || value === null) ? undefined : share_card_text_delay(draft, field);
8335
8842
  const write = Promise.allSettled([prior, delay]).then(async () => {
8336
8843
  if (versions[field] !== version) return;
8337
8844
  await request_json(`/api/rooms/${encodeURIComponent(room_id)}/share-card`, { share_id, edits: { [field]: value } });
8338
- draft.saved_card[field] = value;
8845
+ draft.saved_card[field] = shown;
8339
8846
  });
8340
8847
  share_card_writes.set(key, write);
8341
8848
  try { await write; }
@@ -8359,7 +8866,7 @@ async function browser_share_data(room_id, models) {
8359
8866
  const exported_at = new Date().toISOString();
8360
8867
  const [recorded, configuration] = await Promise.all([record_share_reads(room_id), models || ((state.launch.available || state.remote_rooms)
8361
8868
  ? local_launch_request("room-models", { room_id, quick: true, token: localStorage.getItem(`discuss-access:${room_id}`) }).catch(() => null) : null)]);
8362
- const folders = [configuration?.project_directory, ...(configuration?.extra_directories || [])];
8869
+ const folders = [configuration?.project_directory, ...(configuration?.extra_directories || []).map(extra_directory_path)];
8363
8870
  const responses = share_payload(recorded.responses, room_id, folders);
8364
8871
  // The same page with its messages' attachments listed, used when the owner chooses to include them.
8365
8872
  const responses_with_files = share_payload(recorded.responses, room_id, folders, { attachments: true });
@@ -8736,6 +9243,8 @@ async function backup_rooms({ ids, name }) {
8736
9243
  notify("info", t('已生成 {value1} 个频道的备份,请查看浏览器下载。', { value1: snapshots.length }));
8737
9244
  } catch (error) {
8738
9245
  notify("error", t('导出失败,未生成备份:{value1}', { value1: error.message }));
9246
+ error.notified = true;
9247
+ throw error;
8739
9248
  } finally {
8740
9249
  state.backup_pending = false;
8741
9250
  publish_view();
@@ -8872,19 +9381,19 @@ function change_view_theme(theme) {
8872
9381
  }
8873
9382
 
8874
9383
  window.discuss_view = { snapshot: view_snapshot, write_field: write_view_field, write_create_preferences, notify, load_decision_input, upload_progress,
8875
- write_launch: write_launch_field, default_launch_entry, platform_configured, description_template, save_description_template, description_draft, write_description_draft, clear_card_drafts, preset_origin, describe_member, set_chain_rounds, continue_chain, expert_presets, apply_expert_preset, unique_instance, member_label, default_name, label_draft, write_label_draft, preset_identity, save_expert_preset, delete_expert_preset, write_room_connection, write_room_adapter, launch_clients: LAUNCH_CLIENTS,
9384
+ write_launch: write_launch_field, default_launch_entry, platform_configured, description_template, save_description_template, description_draft, write_description_draft, clear_card_drafts, preset_origin, preset_origin_info, preset_skilled, describe_member, set_chain_rounds, continue_chain, expert_presets, project_presets, load_project_presets, clear_project_presets, apply_expert_preset, unique_instance, member_label, default_name, label_draft, write_label_draft, preset_identity, save_expert_preset, delete_expert_preset, trust_expert_preset, workflow_key, preset_key, write_room_connection, write_room_adapter, launch_clients: LAUNCH_CLIENTS,
8876
9385
  launch_model_state, load_launch_models, write_launch_model, save_launch_api_key, create_launch_project, remove_launch_projects, display_path, write_scheduler, save_scheduler_api_key, save_search_api_key, check_scheduler, write_named_followup, write_create_discussion, write_create_goal, write_create_chain_rounds, write_create_relay_rounds, check_launch_api, launch_summary, launch_can_set_access, full_only_hint, pick_launch_directory, browse_local_directory, list_remote_directories, save_launch_projects, restore_launch_profile, reset_create_form, empty_discussion_message,
8877
9386
  start_drag: start_directory_drag, reconnect: reconnect_live_updates, stop_label, local_request: local_launch_request,
8878
9387
  attachment_markup, attachment_download_link, attachment_size, attachment_file_icon, add_attachments, drop_attachments, paste_attachments, drop_unreferenced_attachments, set_text_preview: (open) => { state.text_preview = open; }, set_image_viewer: (open) => { state.image_viewer = open; }, attachment_url, read_zip_directory,
8879
9388
  write_expert: write_view_expert, add_instance: add_view_instance, add_preset: add_preset_instance, platform_of, execute: execute_view_action, theme: change_view_theme,
8880
- reload_workflows, save_card_preset, import_expert, workflow_preset, write_create_host_workflows, write_create_api_max_requests, write_create_auto_destroy, write_create_image_generation, set_room_api_max_requests, set_room_image_generation, set_room_scheduler, set_room_extra_directories, set_room_project_directory,
9389
+ reload_workflows, trust_project_workflow, confirm_workflow_trust, dismiss_workflow_trust, save_card_preset, import_expert, workflow_preset, write_create_host_workflows, write_create_api_max_requests, write_create_auto_destroy, write_create_image_generation, set_room_api_max_requests, set_room_image_generation, set_room_scheduler, set_room_extra_directories, set_room_project_directory,
8881
9390
  admin: { register: register_admin, login: login_admin, logout: logout_admin,
8882
9391
  update_profile: update_admin_profile, avatar_from_file: admin_avatar_from_file, validate: validate_admin_form,
8883
9392
  sessions: admin_sessions, revoke: revoke_admin_sessions, change_password: change_admin_password },
8884
9393
  device: { request: device_request, pair: pair_this_device, take_scanned: take_scanned_pairing, invite: invite_device, renew: renew_this_device, forget: forget_pairing,
8885
9394
  label: device_label, prompt_confirm: () => state.device.prompt?.run(), prompt_cancel: () => state.device.prompt?.cancel() },
8886
9395
  request: request_json, rewind_plan, identities: IDENTITIES, platform_identity: name => PLATFORM_IDENTITIES[name], display_name, mention_handles, mentioned_members, render_room_markdown, sources: SOURCE_LABELS,
8887
- set_member_access, set_member_model, allow_denials, set_member_adapter, reload_room_models, read_member_skills, read_room_files, manage_room_files, upload_project_file, download_project_file, download_project_folder, room_title, read_room_page, read_room_media, read_execution_details, interject_execution, read_member_chat, send_member_chat, stop_member_chat, pause_execution, limits_label, stop_reason_label, participant_model, participant_files, participant_session_hint, participant_access,
9396
+ set_member_access, set_member_model, allow_denials, set_member_adapter, reload_room_models, load_storage, clean_storage, read_member_skills, read_room_files, manage_room_files, upload_project_file, download_project_file, download_project_folder, room_title, read_room_page, read_room_media, read_execution_details, interject_execution, read_member_chat, send_member_chat, stop_member_chat, pause_execution, limits_label, stop_reason_label, participant_model, participant_files, participant_session_hint, participant_access,
8888
9397
  turn_label, turn_guidance, round_groups, limit_rounds, progress_speaker, brief_meta, max_message_length: MAX_MESSAGE_LENGTH, provenance: message_provenance, format_time };
8889
9398
 
8890
9399
  restore_theme();