ai_co_discuss 0.5.27 → 0.5.29

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.
@@ -6,7 +6,7 @@
6
6
 
7
7
  - **任务有 `host_workflows: true`**:房主给了你主持人权限,`host_permissions` 列出勾选了哪些项,属于这些项的控制你自己处理,不请用户代劳:`execution`(`stop`、`stop-all`、`steer`、`retry`、`withdraw`)、`member_config`(`model`、`adapter`、`label`)、`project_access`(`access`)、`roster`(`invite`、`away`、`remove`、`back`)、`pacing`(`order`、`discussion`、`goal`、`checkin`)、`workflows`(保存并启用工作流)、`create_rooms`(新建房间)。没勾选的项不要试,需要时在回答里请用户勾选;操作被拒时错误会写明缺哪一项。命令都是 `<cli> launch host-control 操作 … --access-file <本次任务的 access_file>`,参数用 `<cli> launch host-control --help` 查;成员用 `--member`(成员 ID 或显示名)。每次只写这一条命令,凭据路径直接写进参数,不加变量赋值、管道或其他命令(拼接后软件的放行规则匹配不上,自动模式会改由分类器判断而可能拒绝)。被你所用软件的权限检查拒绝时,回答里如实写“被我所在软件的权限拦下”,不说成房间要求用户本人操作。
8
8
  - **没有该字段,或你是 API 主持人(没有命令行)**:这些操作请用户在网页上做,或请用户在电脑上“成员与设置 → 协作设置”的“主持人权限”里勾选对应的项。事件记录和执行详情不需要勾选,都能读。
9
- - **始终由用户决定**,需要时在回答里提出:对你自己的打断、改项目权限、暂离、移除或更换主持人(你自己失败的执行按下文处理),批准超出上限的轮数,项目权限高于可写或放行被拒绝的工具,改项目目录,撤回、回退用户的消息,私聊。
9
+ - **始终由用户决定**,需要时在回答里提出:对你自己的打断、改项目权限、暂离、移除或更换主持人(你自己失败的执行按下文处理),批准超出上限的轮数,放行被拒绝的工具,改项目目录,撤回、回退用户的消息,私聊。
10
10
 
11
11
  用户要求停下、换人或调整顺序时直接执行;你自己发现问题时先诊断再处理。每次控制都在回答里说明做了什么、为什么。`revision` 过期会被拒绝,重新读取后再提交。
12
12
 
@@ -25,19 +25,24 @@
25
25
  - 偏了方向或要补充:`steer` 插话(不需要打断时优先)。
26
26
  - 卡住或做错:`stop` 打断。被打断的执行不能 `retry`,它的请求随之取消;要接着做就重新派活,写明已完成的部分与接着做什么。全部停下用 `stop-all`(讨论进行中用 `discussion`)。
27
27
  - 偶发失败(网络、超时、软件崩溃):`retry`。
28
+ - 成员因权限被拒而做不下去(执行详情里的被拒操作,如联网搜索、读项目外文件、跑命令):用 `access` 把它调到够用的档位后重新派活,见下文“按需配置权限”。
28
29
  - 模型限流或不可用:`model` 换模型;App 卡住:`adapter` 切到同一会话的 CLI。
29
30
  - 无法恢复:`remove` 后 `invite` 换一位。
30
31
  - 自己派出的活停不下来、方向错了或用户改了主意:`withdraw --message 派活消息编号`(接力或循环立即停下,不再交回你)。
31
32
 
32
33
  ## 调整成员与推进
33
34
 
34
- `invite` 只用本机已配置的软件(项目权限默认只读、最高可写,返回的新成员本次执行里就能点名);`away` / `remove` / `back`、`access`、`label`(`--label` 改显示名,`--description` 改分工描述)调整成员。`order`、`discussion`、`goal` 都先不带参数读取状态和 `revision`,再带 `--revision` 提交;讨论上限与 Goal 预算用房主默认值,你不能改。Goal 只在任务需要房间空闲时持续推进、且目标和完成标准明确时开。
35
+ `invite` 只用本机已配置的软件(项目权限默认只读,返回的新成员本次执行里就能点名);`away` / `remove` / `back`、`access`、`label`(`--label` 改显示名,`--description` 改分工描述)调整成员。`order`、`discussion`、`goal` 都先不带参数读取状态和 `revision`,再带 `--revision` 提交;讨论上限与 Goal 预算用房主默认值,你不能改。Goal 只在任务需要房间空闲时持续推进、且目标和完成标准明确时开。
36
+
37
+ ### 按需配置权限
38
+
39
+ 成员的项目权限按它这次的任务给,够用即可:只读(读项目、回答)→ 可写(改项目文件、跑命令)→ 自动(软件自带分类器逐次放行项目外读写、联网等)→ 全放开(跳过全部检查)。邀请、新建房间时按分工定档;真出现权限问题(执行详情里有被拒操作)再调高到能解决的那一档,不预先给最高档。软件不支持的档位会被拒绝(如 Antigravity CLI 没有自动档,后台跑命令只能靠全放开)。开到全放开时在回答里写明给了谁、为什么。(成员会读外部内容、可能被注入,档位越高出事的范围越大。)
35
40
 
36
41
  ## 新建房间
37
42
 
38
43
  勾选了 `create_rooms` 时,一部分工作需要独立的成员、会话与记录(用户要求另开房间,或一条支线会长期占住本房间)时,可以 `create-room` 拆出去:`--title`(必填)、`--goal`、`--members 平台,平台`、`--host 平台`(用户指定了主持人才填,不填即与你同款的专家)、`--cwd`(只能是本房间项目目录或其子目录)、`--access read|write`(默认只读)、`--host-model` 与 `--host-effort` 可指定主持人模型和档位;同一平台可在成员名单中重复出现,每位独立编号。`--text` 或 `--body-file UTF-8文件`(主持人项目或草稿目录内)提供首条消息(写清要它做什么、做完怎样算完成)。返回新房间编号;失败或不确定是否建成时沿用同一 `--submission-id` 重试,不会重复建房。本房间可新建的数量有上限,新房间直接复制本房间的智能调度、生图、API 上限、连续派活上限与主持人权限(不含 `create_rooms`,不能再新建房间)。
39
44
 
40
- 先用 `room list --query 标题片段` 或用户给的链接确定目标;同名时查看房间确认。用 `launch host-control rooms` 核对关联、对方主持人、忙闲、投递状态和互传余额。尚未关联时,用 `launch host-control link-request --room 编号 --reason 理由` 请房主批准,收到批准通知后发原消息。
45
+ 先用 `room list --query 标题片段` 或用户给的房间编号找到同一站点上的目标房间,同名时查看房间确认。直接用下面的 `room-post` 发给对方主持人。`launch host-control rooms` 只列本房的父房间和子房间。
41
46
 
42
47
  用 `launch host-control room-post --room 编号 --body-file FILE --expect reply` 交给对方主持人,普通通知用 `--expect none`;短消息可用 `--text`。对方忙时排队,只有父房间能用 `--interrupt` 打断子房间。达到互传上限时,请房主决定是否继续。
43
48
 
@@ -4362,7 +4362,7 @@ def interrupt_for_message(connection, room_id, message_id):
4362
4362
  now = int(time.time())
4363
4363
  source = connection.execute("""SELECT r.title FROM message_relays m JOIN rooms r ON r.id=m.source_room_id
4364
4364
  WHERE m.message_id=?""", (message_id,)).fetchone()
4365
- notice = (Text("关联房间「{room}」的主持人刚发来消息 #{message_id},请先读原文。", room=source[0], message_id=message_id)
4365
+ notice = (Text("房间「{room}」的主持人刚发来消息 #{message_id},请先读原文。", room=source[0], message_id=message_id)
4366
4366
  if source else Text("用户刚发来消息 #{message_id},请先读原文,在这一轮的回答里一并处理。", message_id=message_id))
4367
4367
  for row in steerable:
4368
4368
  execution = connection.execute("SELECT * FROM member_executions WHERE id=?", (row["execution_id"],)).fetchone()
@@ -4600,8 +4600,6 @@ def record_relay_send(connection, room_id, token, payload):
4600
4600
  begin_write(connection)
4601
4601
  target = payload.get("target_room_id")
4602
4602
  host = linked_room_values(connection, room_id, target, payload.get("host"))
4603
- if not connection.execute("SELECT 1 FROM room_links WHERE room_id=? AND other_room_id=?", (room_id, target)).fetchone():
4604
- raise PermissionError(Text("只有互相关联的房间之间才能代主持人发言"))
4605
4603
  text, member = payload.get("text"), payload.get("member", "")
4606
4604
  if not isinstance(text, str) or not text.strip() or len(text.strip()) > 32000 or not isinstance(member, str):
4607
4605
  raise ValueError(Text("发信留痕须包含有效的正文与成员名称"))
@@ -4739,7 +4737,7 @@ def relay_count(connection, room_id, source):
4739
4737
 
4740
4738
 
4741
4739
  def check_relay(connection, room_id, relay):
4742
- """Check a message another room's host sends here: the rooms are linked, and the hosts have not passed the limit.
4740
+ """Validate the source room, reply reference, and the pair's message limit.
4743
4741
 
4744
4742
  `relay.limit` is the owner's limit the runner reads from this computer's preferences (0 or absent: unlimited, user
4745
4743
  2026-11-21). It counts both directions since the owner's own last message in either room; past it the write is a 409
@@ -4753,8 +4751,6 @@ def check_relay(connection, room_id, relay):
4753
4751
  source, limit = relay["room_id"], relay.get("limit", 0)
4754
4752
  if type(limit) is not int or not 0 <= limit <= MAX_RELAY_LIMIT:
4755
4753
  raise ValueError(Text("relay.limit 须为 0–100 的整数,0 表示不限"))
4756
- if not connection.execute("SELECT 1 FROM room_links WHERE room_id=? AND other_room_id=?", (room_id, source)).fetchone():
4757
- raise PermissionError(Text("只有互相关联的房间之间才能代主持人发言"))
4758
4754
  if relay.get("expect", "reply") not in ("reply", "none"):
4759
4755
  raise ValueError(Text("expect 须为 reply 或 none"))
4760
4756
  reply_to = relay.get("reply_to")
@@ -1,50 +1,7 @@
1
- """Owner-managed peer rooms and host requests to link existing rooms."""
1
+ """Parent and child rooms visible to their host or owner."""
2
2
 
3
- import re
4
- import uuid
5
-
6
- from .free_room import linked_room_values, member_display_names, relay_count, require_owner_or_host, wake_host
3
+ from .free_room import member_display_names, relay_count
7
4
  from .message_queue import host_busy
8
- from .runtime import begin_write, require_owner
9
- from .texts import Text, save_text
10
-
11
-
12
- def request_view(db, room, message_id):
13
- """Read one application within its source room."""
14
- row = db.execute("""SELECT q.message_id AS id,q.target_room_id AS room_id,r.title,q.reason,q.state
15
- FROM room_link_requests q JOIN messages m ON m.id=q.message_id
16
- LEFT JOIN rooms r ON r.id=q.target_room_id WHERE m.room_id=? AND m.id=?""", (room, message_id)).fetchone()
17
- if not row:
18
- raise LookupError(Text("找不到关联申请"))
19
- return dict(row)
20
-
21
-
22
- def card(db, room, source, text, key):
23
- """Append a system card without routing it to members."""
24
- mid = db.execute("""INSERT INTO messages(room_id,author,text,source,submission_id,created_at)
25
- VALUES (?,'系统',?,?,?,strftime('%Y-%m-%dT%H:%M:%SZ','now'))""", (room, text, source, key)).lastrowid
26
- db.execute("INSERT INTO message_details(message_id,kind,submitted_by) VALUES (?,'notice','系统')", (mid,))
27
- save_text(db, "message", mid, "text", text)
28
- return mid
29
-
30
-
31
- def change_peer(db, room, other, remove):
32
- """Write both sides together while holding the transaction's writer lock."""
33
- linked_room_values(db, room, other, "peer")
34
- for source, dest in ((room, other), (other, room)):
35
- row = db.execute("SELECT relation FROM room_links WHERE room_id=? AND other_room_id=?", (source, dest)).fetchone()
36
- if remove and (not row or row[0] != "peer"):
37
- raise ValueError(Text("只能解除已有的平级关联"))
38
- if not remove and row:
39
- raise FileExistsError(Text("两个房间已经关联"))
40
- title = db.execute("SELECT title FROM rooms WHERE id=?", (dest,)).fetchone()[0]
41
- text = Text("已解除与房间「{title}」的关联。", title=title) if remove else Text("已关联房间「{title}」。", title=title)
42
- mid = card(db, source, "room_link", text, uuid.uuid4().hex)
43
- if remove:
44
- db.execute("DELETE FROM room_links WHERE room_id=? AND other_room_id=?", (source, dest))
45
- else:
46
- db.execute("INSERT INTO room_links VALUES (?,?,?,'peer','')", (mid, source, dest))
47
- return {"ok": True}
48
5
 
49
6
 
50
7
  def list_links(db, room, limit=0):
@@ -61,65 +18,3 @@ def list_links(db, room, limit=0):
61
18
  result.append(dict(row) | {"host": member_display_names(db, dest).get(row["host"]), "busy": bool(host_busy(db, dest)), "outbound": list(map(dict, receipts)),
62
19
  "relay_used": used, "relay_remaining": max(0, limit - used) if limit else None})
63
20
  return {"links": result}
64
-
65
-
66
- def apply_link(db, room, token, body):
67
- """Record a host's idempotent request without granting access."""
68
- if not require_owner_or_host(db, room, token):
69
- raise PermissionError(Text("只有当前主持人可以申请关联"))
70
- other, reason, key = body.get("room_id"), body.get("reason"), body.get("submission_id")
71
- linked_room_values(db, room, other, "peer")
72
- if not isinstance(reason, str) or not reason.strip() or len(reason) > 32000 or not isinstance(key, str) or not re.fullmatch(r"[a-zA-Z0-9_-]{8,100}", key):
73
- raise ValueError(Text("需要有效的申请理由和提交编号"))
74
- old = db.execute("SELECT id FROM messages WHERE room_id=? AND submission_id=?", (room, key)).fetchone()
75
- if old:
76
- view = request_view(db, room, old[0])
77
- if (view["room_id"], view["reason"]) != (other, reason):
78
- raise FileExistsError(Text("这个提交编号已被另一条内容使用,请为新发言生成新编号"))
79
- return view
80
- if db.execute("SELECT 1 FROM room_links WHERE room_id=? AND other_room_id=?", (room, other)).fetchone():
81
- raise FileExistsError(Text("两个房间已经关联"))
82
- mid = card(db, room, "room_link_request", reason, key)
83
- db.execute("INSERT INTO room_link_requests VALUES (?,?,?,'pending')", (mid, other, reason))
84
- return request_view(db, room, mid)
85
-
86
-
87
- def handle_links(db, room, token, path, method, body, site_owner, target_token, limit=0):
88
- """Dispatch link management with source and destination ownership checks."""
89
- if path == ["room-links"] and method == "GET":
90
- require_owner_or_host(db, room, token)
91
- if not 0 <= limit <= 100:
92
- raise ValueError(Text("relay.limit 须为 0–100 的整数,0 表示不限"))
93
- return list_links(db, room, limit)
94
- begin_write(db)
95
- if path == ["room-link-requests"] and method == "POST":
96
- return apply_link(db, room, token, body)
97
- require_owner(db, room, token)
98
- decision = len(path) == 3 and path[0] == "room-link-requests" and path[2] == "decide" and method == "POST"
99
- if decision:
100
- req = request_view(db, room, int(path[1]))
101
- other = req["room_id"]
102
- if type(body.get("approve")) is not bool:
103
- raise ValueError(Text("approve 须为布尔值"))
104
- elif path == ["room-links"] and method == "POST":
105
- other = body.get("room_id")
106
- elif len(path) == 2 and path[0] == "room-links" and method == "DELETE":
107
- other = path[1]
108
- else:
109
- raise LookupError(Text("接口不存在"))
110
- if not site_owner and (not decision or body["approve"]):
111
- require_owner(db, other, target_token)
112
- if not decision:
113
- return change_peer(db, room, other, method == "DELETE" or body.get("action") == "delete")
114
- state = "approved" if body["approve"] else "declined"
115
- if req["state"] == state:
116
- return req
117
- if req["state"] != "pending":
118
- raise FileExistsError(Text("申请已经处理"))
119
- if body["approve"]:
120
- change_peer(db, room, other, False)
121
- db.execute("UPDATE room_link_requests SET state=? WHERE message_id=?", (state, req["id"]))
122
- notice = (Text("与房间 {room} 的关联已批准,可以发送消息。", room=other) if body["approve"]
123
- else Text("与房间 {room} 的关联申请已拒绝。", room=other))
124
- wake_host(db, room, req["id"], notice, f"peer-link-{req['id']}")
125
- return request_view(db, room, req["id"])
@@ -76,6 +76,8 @@ CREATE TABLE IF NOT EXISTS attachments (
76
76
  -- Pixel size as shown (EXIF rotation applied) of PNG/JPEG/GIF/WebP images; 0 when the header gives none,
77
77
  -- NULL when not measured yet.
78
78
  width INTEGER, height INTEGER,
79
+ -- The type (image/webp or image/jpeg) of a smaller copy a page made for showing in messages; NULL when none.
80
+ thumbnail_type TEXT,
79
81
  UNIQUE(room_id, submission_id)
80
82
  );
81
83
  CREATE INDEX IF NOT EXISTS attachments_message ON attachments(message_id, position);
@@ -114,16 +116,10 @@ CREATE TABLE IF NOT EXISTS room_links (
114
116
  message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
115
117
  room_id TEXT NOT NULL REFERENCES rooms(id),
116
118
  other_room_id TEXT NOT NULL,
117
- relation TEXT NOT NULL CHECK(relation IN ('child','parent','peer')),
119
+ relation TEXT NOT NULL CHECK(relation IN ('child','parent')),
118
120
  host TEXT NOT NULL,
119
121
  UNIQUE(room_id, other_room_id)
120
122
  );
121
- CREATE TABLE IF NOT EXISTS room_link_requests (
122
- message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
123
- target_room_id TEXT NOT NULL,
124
- reason TEXT NOT NULL,
125
- state TEXT NOT NULL CHECK(state IN ('pending','approved','declined'))
126
- );
127
123
  -- Sender-side receipts survive deletion of the destination room.
128
124
  CREATE TABLE IF NOT EXISTS room_relay_sends (
129
125
  message_id INTEGER PRIMARY KEY REFERENCES messages(id) ON DELETE CASCADE,
package/backend/server.py CHANGED
@@ -27,7 +27,7 @@ from contextlib import closing
27
27
  from datetime import datetime, timedelta, timezone
28
28
  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
29
29
  from pathlib import Path
30
- from urllib.parse import parse_qs, quote, urlsplit
30
+ from urllib.parse import parse_qs, quote, unquote, urlsplit
31
31
 
32
32
  from .entry_guard import (BROWSER_COOKIE_SECONDS, HELLO_PATH, OPEN_PATH, PUBLIC_PATHS, EntryPolicy, answer_hello, browser_admitted,
33
33
  browser_cookie_name, open_link_key, proof, request_proven)
@@ -56,7 +56,8 @@ from .visual_fences import fold_message_visuals
56
56
  from .identity import MAX_ROOM_AGENTS, PARTICIPANTS, default_label_text, is_ai, is_participant
57
57
  from .message_queue import drain as drain_queue, enqueue, enqueue_share, queue_action, queue_split, queue_view
58
58
  from .room_import import import_room, imported_attachment
59
- from .room_links import handle_links, request_view
59
+ from .room_links import list_links
60
+ from .free_room import require_owner_or_host
60
61
  from .runtime import (begin_write, limit_values, owner_proxy_token, require_owner, token_hash,
61
62
  enforce_session_limits, room_limits_view, session_limits_view)
62
63
  from .goal_room import goal_action, goal_view
@@ -77,6 +78,13 @@ MAX_BODY_BYTES = 512 * 1024
77
78
  MAX_FILE_PART_BODY_BYTES = 5 * 1024 * 1024
78
79
  MAX_IMPORT_BYTES = 32 * 1024 * 1024
79
80
  MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
81
+ # A smaller copy of an image a page made (WebP or JPEG), shown in messages in place of the original: at most this many
82
+ # bytes and this many pixels on its longer side, and its shape within THUMBNAIL_RATIO_TOLERANCE of the original's.
83
+ MAX_THUMBNAIL_BYTES = 512 * 1024
84
+ MAX_THUMBNAIL_SIDE = 1600
85
+ THUMBNAIL_RATIO_TOLERANCE = 0.03
86
+ THUMBNAIL_TYPES = ("image/webp", "image/jpeg")
87
+ THUMBNAIL_SUFFIX = ".thumbnail"
80
88
  # Files uploaded while the message is still being written are dropped if never sent within this time.
81
89
  UNSENT_ATTACHMENT_TTL = timedelta(hours=24)
82
90
  ATTACHMENT_SWEEP_SECONDS = 6 * 60 * 60
@@ -104,6 +112,12 @@ DIRECTORY_PICKER_TIMEOUT = 600 # the folder dialog waits for the person at the
104
112
  FILE_CHUNK_BYTES = 1024 * 1024
105
113
  # A project media file the local page plays is served by a random ticket for this long after the runner checked access.
106
114
  MEDIA_TICKET_SECONDS = 600
115
+ # A project page the computer's own browser opens in a tab keeps reading the files beside it (lazy images, scripts) for
116
+ # this long; its address is a random ticket naming the project folder, never a path.
117
+ PAGE_TICKET_SECONDS = 12 * 3600
118
+ # The page runs as an opaque origin (no allow-same-origin), so it can read nothing of this site; it may run its scripts,
119
+ # open pop-ups and dialogs, and load anything from the folder or the web. No forms: a write to this site needs its origin.
120
+ PAGE_POLICY = "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads"
107
121
  MAX_MEDIA_TICKETS = 64
108
122
  MAX_TEXT_LENGTH = 32000
109
123
  SESSION_ID_PATTERN = re.compile(r"[0-9A-Za-z_-]{8,128}")
@@ -542,13 +556,7 @@ def init_database(database, seed=True):
542
556
  connection.executescript(SCHEMA)
543
557
  if 'member' not in {row[1] for row in connection.execute('PRAGMA table_info(message_relays)')}:
544
558
  connection.execute("ALTER TABLE message_relays ADD COLUMN member TEXT NOT NULL DEFAULT ''")
545
- links_schema = connection.execute("SELECT sql FROM sqlite_master WHERE name='room_links'").fetchone()[0]
546
- if "'peer'" not in links_schema:
547
- begin_write(connection)
548
- connection.execute("ALTER TABLE room_links RENAME TO old_room_links")
549
- connection.execute(links_schema.replace("'child','parent'", "'child','parent','peer'"))
550
- connection.execute("INSERT INTO room_links SELECT * FROM old_room_links")
551
- connection.execute("DROP TABLE old_room_links")
559
+ connection.execute("DELETE FROM room_links WHERE relation='peer'")
552
560
  relay_columns = {row[1] for row in connection.execute("PRAGMA table_info(message_relays)")}
553
561
  if "expect" not in relay_columns:
554
562
  connection.execute("ALTER TABLE message_relays ADD COLUMN expect TEXT NOT NULL DEFAULT 'reply'")
@@ -579,6 +587,8 @@ def init_database(database, seed=True):
579
587
  for name in ("width", "height"):
580
588
  if name not in attachment_columns:
581
589
  connection.execute(f"ALTER TABLE attachments ADD COLUMN {name} INTEGER")
590
+ if "thumbnail_type" not in attachment_columns:
591
+ connection.execute("ALTER TABLE attachments ADD COLUMN thumbnail_type TEXT")
582
592
  if connection.execute("INSERT OR IGNORE INTO site_preferences (key,value) VALUES ('child_folders_migrated','1')").rowcount:
583
593
  connection.execute("""UPDATE room_folder_assignments AS child SET folder_id=parent.folder_id
584
594
  FROM room_links l JOIN room_folder_assignments parent ON parent.room_id=l.other_room_id
@@ -1844,6 +1854,7 @@ def finish_destruction_files(database, room_id):
1844
1854
  for file_id in files.get("ids", []):
1845
1855
  path = attachment_path(database, {"id": file_id})
1846
1856
  try:
1857
+ thumbnail_path(database, {"id": file_id}).unlink(missing_ok=True)
1847
1858
  path.unlink(missing_ok=True)
1848
1859
  except OSError:
1849
1860
  logging.exception("Attachment cleanup failed: %s", file_id)
@@ -2326,6 +2337,8 @@ def attachment_view(row):
2326
2337
  result = dict(row)
2327
2338
  base = f"/api/rooms/{result['room_id']}/attachments/{result['id']}/content"
2328
2339
  result.update(url=base, download_url=base + "?download=1")
2340
+ if result.get("thumbnail_type"):
2341
+ result["thumbnail_url"] = f"/api/rooms/{result['room_id']}/attachments/{result['id']}/thumbnail"
2329
2342
  return result
2330
2343
 
2331
2344
 
@@ -2380,8 +2393,6 @@ def message_with_attachments(connection, row):
2380
2393
  if message["withdrawn"] == "retracted":
2381
2394
  # The owner retracted it before anyone handled it: only the page that retracted it keeps the text.
2382
2395
  return {**message, "text": "", "summary": "", "suggestions": [], "attachments": []}
2383
- if message["source"] == "room_link_request":
2384
- message["link_request"] = request_view(connection, message["room_id"], message["id"])
2385
2396
  message["texts"] = load_texts(connection, "message", message["id"])
2386
2397
  message["suggestions"] = message_suggestions(connection, message["id"])
2387
2398
  files = with_image_sizes(connection, connection.execute("SELECT * FROM attachments WHERE message_id=? ORDER BY position,id",
@@ -2447,6 +2458,43 @@ def attachment_path(database, attachment):
2447
2458
  return root / attachment["id"]
2448
2459
 
2449
2460
 
2461
+ def thumbnail_path(database, attachment):
2462
+ """Where the smaller copy of an image attachment is kept, beside the original."""
2463
+ return attachment_path(database, {"id": attachment["id"] + THUMBNAIL_SUFFIX})
2464
+
2465
+
2466
+ def store_attachment_thumbnail(connection, database, room_id, identifier, token, data):
2467
+ """Keep the smaller copy of an image attachment a room participant's page made; the first one stored stays.
2468
+
2469
+ The site cannot decode images, so it checks what it can read from the headers: a WebP or JPEG no larger than
2470
+ MAX_THUMBNAIL_SIDE pixels, smaller than the original, with the original's shape.
2471
+
2472
+ Returns:
2473
+ {"attachment": the attachment with its thumbnail_url, "duplicate": whether a thumbnail was already kept}.
2474
+ """
2475
+ begin_write(connection)
2476
+ try:
2477
+ require_owner(connection, room_id, token)
2478
+ except PermissionError:
2479
+ require_member(connection, room_id, token)
2480
+ attachment = get_attachment(connection, room_id, identifier)
2481
+ if attachment.get("thumbnail_type"):
2482
+ return {"attachment": attachment, "duplicate": True}
2483
+ content_type = attachment_content_type(data)
2484
+ width, height = image_size(io.BytesIO(data))
2485
+ original_width, original_height = attachment.get("width") or 0, attachment.get("height") or 0
2486
+ if (attachment["content_type"] not in SIZED_IMAGE_TYPES or content_type not in THUMBNAIL_TYPES or not width
2487
+ or max(width, height) > MAX_THUMBNAIL_SIDE or len(data) >= attachment["size"] or not original_width
2488
+ or abs(width / height - original_width / original_height) > THUMBNAIL_RATIO_TOLERANCE * original_width / original_height):
2489
+ raise ValueError(Text('缩略图不符合要求'))
2490
+ path = thumbnail_path(database, attachment)
2491
+ path.parent.mkdir(parents=True, exist_ok=True)
2492
+ path.write_bytes(data)
2493
+ connection.execute("UPDATE attachments SET thumbnail_type=? WHERE id=?", (content_type, identifier))
2494
+ connection.commit()
2495
+ return {"attachment": get_attachment(connection, room_id, identifier), "duplicate": False}
2496
+
2497
+
2450
2498
  def store_attachment(connection, database, room_id, metadata, data):
2451
2499
  """Persist one immutable upload; exact retries return the original file."""
2452
2500
  begin_write(connection)
@@ -2491,6 +2539,7 @@ def remove_attachment_files(connection, database, rows):
2491
2539
  for row in rows:
2492
2540
  connection.execute("DELETE FROM attachments WHERE id=? AND message_id IS NULL", (row["id"],))
2493
2541
  attachment_path(database, row).unlink(missing_ok=True)
2542
+ thumbnail_path(database, row).unlink(missing_ok=True)
2494
2543
 
2495
2544
 
2496
2545
  def prune_unsent_attachments(connection, database, room_id):
@@ -2524,11 +2573,13 @@ def sweep_attachments(database):
2524
2573
  registered = {os.path.normcase(row[0]) for row in connection.execute("SELECT id FROM attachments")}
2525
2574
  cutoff = time.time() - ORPHAN_ATTACHMENT_GRACE_SECONDS
2526
2575
  for path in root.iterdir():
2527
- if os.path.normcase(path.name) in registered:
2576
+ # A thumbnail goes with its original.
2577
+ name = path.name.removesuffix(THUMBNAIL_SUFFIX)
2578
+ if os.path.normcase(name) in registered:
2528
2579
  continue
2529
2580
  try:
2530
2581
  info = path.lstat()
2531
- if stat.S_ISREG(info.st_mode) and (path.name in expired or info.st_mtime < cutoff):
2582
+ if stat.S_ISREG(info.st_mode) and (name in expired or info.st_mtime < cutoff):
2532
2583
  path.unlink()
2533
2584
  except FileNotFoundError:
2534
2585
  pass
@@ -2781,6 +2832,8 @@ def append_message(connection, room_id, payload, actor):
2781
2832
  room = require_room(connection, room_id)
2782
2833
  if not payload.get("relay"):
2783
2834
  return append_free_message(connection, room, payload, actor)
2835
+ if room["archived"]:
2836
+ raise FileExistsError(Text("房间已存档,不再投递"))
2784
2837
  if payload.get("interrupt") is not True:
2785
2838
  return append_free_message(connection, room, {**payload, "queue": True}, actor)
2786
2839
  relay = payload["relay"]
@@ -3455,6 +3508,8 @@ class DiscussionServer(ThreadingHTTPServer):
3455
3508
  self.local_launch = local_launch
3456
3509
  # Project media the local page may play: ticket -> (path, size, mtime_ns, content_type, name, expires).
3457
3510
  self.media_tickets = {}
3511
+ # Project pages opened in a tab of the computer's own browser: ticket -> (project folder, expires).
3512
+ self.page_tickets = {}
3458
3513
  self.media_lock = threading.Lock()
3459
3514
  self.local_site = not hub and address[0] in ("127.0.0.1", "::1", "localhost")
3460
3515
  self.admin_setup_key = os.getenv("DISCUSS_ADMIN_SETUP_KEY") or secrets.token_urlsafe(18)
@@ -3697,6 +3752,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3697
3752
  self.bridged = self.relay_bridge(parts)
3698
3753
  if parts[:3] == ["api", "local", "media"] and len(parts) == 4 and method == "GET":
3699
3754
  return self.serve_media_ticket(parts[3])
3755
+ if parts[:3] == ["api", "local", "page"] and len(parts) >= 5 and method == "GET":
3756
+ return self.serve_page_ticket(parts[3], parts[4:])
3700
3757
  if parts[:2] == ["api", "local"]:
3701
3758
  return self.handle_local_launch(parts, method)
3702
3759
  if parts == ["api", "updates"] and method == "GET":
@@ -3741,10 +3798,6 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3741
3798
  """Handle read-only GET requests."""
3742
3799
  self.dispatch("GET")
3743
3800
 
3744
- def do_DELETE(self):
3745
- """Remove an existing peer link."""
3746
- self.dispatch("DELETE")
3747
-
3748
3801
  def do_POST(self):
3749
3802
  """Handle JSON mutations and explicit binary attachment uploads."""
3750
3803
  self.dispatch("POST")
@@ -3936,9 +3989,12 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3936
3989
 
3937
3990
  The page never learns the file's path; the ticket names one file as it was checked and expires.
3938
3991
  """
3992
+ if payload.get("page") is True:
3993
+ return self.issue_page_ticket(payload)
3939
3994
  status, result = self.local_command_result("room-media", payload)
3940
3995
  if status != 200:
3941
3996
  return self.respond(result, status)
3997
+ result.pop("directory", None)
3942
3998
  path = Path(result.pop("file"))
3943
3999
  info = path.stat()
3944
4000
  ticket = secrets.token_urlsafe(32)
@@ -3954,6 +4010,48 @@ class DiscussionHandler(BaseHTTPRequestHandler):
3954
4010
  tickets[ticket] = (path, info.st_size, info.st_mtime_ns, result["content_type"], path.name, now + MEDIA_TICKET_SECONDS, disposition)
3955
4011
  return self.respond({**result, "url": f"/api/local/media/{ticket}"})
3956
4012
 
4013
+ def issue_page_ticket(self, payload):
4014
+ """Open a project HTML file in a tab of this computer's browser straight from disk, with the files beside it.
4015
+
4016
+ The runner checks the member's access to the file as for media; the ticket names the project folder, and the
4017
+ address mirrors the file's place in it, so relative references resolve inside the folder.
4018
+ """
4019
+ if not re.search(r"\.html?$", str(payload.get("path", "")), re.I):
4020
+ raise ValueError(Text('只能打开 HTML 文件'))
4021
+ status, result = self.local_command_result("room-media", {**{key: value for key, value in payload.items() if key != "page"}, "download": True})
4022
+ if status != 200:
4023
+ return self.respond(result, status)
4024
+ root, path = Path(result["directory"]).resolve(), Path(result["file"]).resolve()
4025
+ ticket = secrets.token_urlsafe(32)
4026
+ now = time.time()
4027
+ with self.server.media_lock:
4028
+ tickets = self.server.page_tickets
4029
+ for key in [key for key, item in tickets.items() if item[1] <= now]:
4030
+ del tickets[key]
4031
+ while len(tickets) >= MAX_MEDIA_TICKETS:
4032
+ del tickets[next(iter(tickets))]
4033
+ tickets[ticket] = (root, now + PAGE_TICKET_SECONDS)
4034
+ relative = "/".join(quote(part) for part in path.relative_to(root).parts)
4035
+ return self.respond({"url": f"/api/local/page/{ticket}/{relative}"})
4036
+
4037
+ def serve_page_ticket(self, ticket, parts):
4038
+ """Serve one file of the project folder a page ticket names, sandboxed; nothing outside the folder."""
4039
+ with self.server.media_lock:
4040
+ item = self.server.page_tickets.get(ticket)
4041
+ if not item or item[1] <= time.time():
4042
+ raise LookupError(Text('页面地址已过期,请重新打开文件'))
4043
+ root = item[0]
4044
+ names = [unquote(part) for part in parts]
4045
+ if any(name in ("", ".", "..") or ":" in name or "\\" in name for name in names):
4046
+ raise LookupError(Text('文件不存在'))
4047
+ path = root.joinpath(*names).resolve()
4048
+ if not path.is_relative_to(root) or not path.is_file():
4049
+ raise LookupError(Text('文件不存在'))
4050
+ content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
4051
+ if content_type.startswith("text/") or content_type in ("application/javascript", "application/json"):
4052
+ content_type += "; charset=utf-8"
4053
+ self.send_file(path, content_type, path.name, "inline", policy=PAGE_POLICY)
4054
+
3957
4055
  def serve_media_ticket(self, ticket):
3958
4056
  """Stream the project media file a ticket names, refusing it once expired or changed since it was checked."""
3959
4057
  with self.server.media_lock:
@@ -4265,24 +4363,37 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4265
4363
  connection.commit()
4266
4364
  return self.respond(result)
4267
4365
  self.refuse_read_only(parts, method)
4268
- supplied_room_token = self.headers.get("X-Discussion-Token")
4269
4366
  self.admin_as_owner(connection, room_id)
4270
4367
  token = self.headers.get("X-Discussion-Token", "")
4271
4368
  if self.headers.get("X-Discussion-Session"):
4272
4369
  record_reported_session(connection, room_id, token, {"session_id": self.headers.get("X-Discussion-Session"),
4273
4370
  "session_client": self.headers.get("X-Discussion-Session-Client")})
4274
4371
  connection.commit()
4275
- if parts[3:4] in (["room-links"], ["room-link-requests"]):
4276
- site_owner = (self.bridged or session_valid(connection, self.admin_token()) or
4277
- (not supplied_room_token and self.local_visitor()))
4278
- body = self.read_payload() if method == "POST" else {}
4279
- result = handle_links(connection, room_id, token, parts[3:], method, body, site_owner,
4280
- body.get("other_token") or self.headers.get("X-Target-Room-Token", token),
4281
- int(params.get("limit", 0)))
4372
+ if parts[3:] == ["room-links"] and method == "GET":
4373
+ require_owner_or_host(connection, room_id, token)
4374
+ limit = int(params.get("limit", 0))
4375
+ if not 0 <= limit <= 100:
4376
+ raise ValueError(Text("relay.limit 须为 0–100 的整数,0 表示不限"))
4377
+ return self.respond(list_links(connection, room_id, limit))
4378
+ if parts[3:] == ["host-room-post"] and method == "POST":
4379
+ require_owner(connection, room_id, token)
4380
+ host = require_member(connection, room_id, self.headers.get(ACTING_MEMBER_HEADER))
4381
+ if host["role"] != "host":
4382
+ raise PermissionError(Text("只有房主或当前主持人可以读取"))
4383
+ body = self.read_payload()
4384
+ target = body.get("target_room_id")
4385
+ relay = {key: body[key] for key in ("limit", "expect", "reply_to") if key in body}
4386
+ relay.update(room_id=room_id, member=host["name"], host=member_display_names(connection, room_id)[host["name"]])
4387
+ payload = dict(author="用户", text=body.get("text"), submission_id=body.get("submission_id"),
4388
+ interrupt=body.get("interrupt", False), relay=relay)
4389
+ result = append_message(connection, target, payload, "用户")
4390
+ drain_room_queue(connection, target)
4282
4391
  connection.commit()
4283
- if method != "GET":
4284
- self.server.hub.notify_update()
4285
- return self.respond(result)
4392
+ self.server.hub.notify_update(target)
4393
+ receipt = {key: result[key] for key in ("queued", "interrupted", "reason") if key in result}
4394
+ if result.get("message"):
4395
+ receipt["message"] = {"id": result["message"]["id"]}
4396
+ return self.respond(receipt)
4286
4397
  if parts[3:4] == ["external-members"]:
4287
4398
  result, status = external_owner_api(connection, room_id, parts[4:], params, method, token, self.read_payload)
4288
4399
  # Revoking (or finding expired) the member that held the room frees it: messages queued behind it go now.
@@ -4561,6 +4672,15 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4561
4672
  return self.respond(discard_attachment(connection, self.server.database, room_id, parts[4], self.headers.get("X-Discussion-Token", "")))
4562
4673
  if method == "POST" and len(parts) == 6 and parts[5] == "import":
4563
4674
  return self.import_attachment(connection, room_id, parts[4])
4675
+ if method == "POST" and len(parts) == 6 and parts[5] == "thumbnail":
4676
+ length = int(self.headers.get("Content-Length", "-1"))
4677
+ if not 0 < length <= MAX_THUMBNAIL_BYTES:
4678
+ return self.respond({"error": Text('缩略图不符合要求')}, 413)
4679
+ data = self.rfile.read(length)
4680
+ if len(data) != length:
4681
+ raise ValueError(Text('附件内容不完整'))
4682
+ return self.respond(store_attachment_thumbnail(connection, self.server.database, room_id, parts[4],
4683
+ self.headers.get("X-Discussion-Token", ""), data))
4564
4684
  if method == "GET" and len(parts) in (5, 6):
4565
4685
  attachment = get_attachment(connection, room_id, parts[4], params, self.headers.get("X-Discussion-Token", ""),
4566
4686
  content=len(parts) == 6)
@@ -4568,6 +4688,11 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4568
4688
  return self.respond(attachment)
4569
4689
  if parts[5] == "content":
4570
4690
  return self.respond_attachment(attachment, params.get("download") == "1")
4691
+ if parts[5] == "thumbnail":
4692
+ path = thumbnail_path(self.server.database, attachment)
4693
+ if not attachment.get("thumbnail_type") or not path.is_file():
4694
+ raise LookupError(Text('附件不存在'))
4695
+ return self.send_file(path, attachment["thumbnail_type"], attachment["file_name"], "inline")
4571
4696
  if parts[5] == "zip":
4572
4697
  path = attachment_path(self.server.database, attachment)
4573
4698
  if not path.is_file():
@@ -4602,8 +4727,11 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4602
4727
  disposition = "attachment" if download or attachment["content_type"] == "application/octet-stream" else "inline"
4603
4728
  self.send_file(path, attachment["content_type"], attachment["file_name"], disposition, {"X-Content-SHA256": attachment["sha256"]})
4604
4729
 
4605
- def send_file(self, path, content_type, file_name, disposition, extra=None, data=None):
4606
- """Send one stored file, or the single byte range a player asks for, never as executable content."""
4730
+ def send_file(self, path, content_type, file_name, disposition, extra=None, data=None, policy="default-src 'none'; sandbox"):
4731
+ """Send one stored file, or the single byte range a player asks for, never as executable content.
4732
+
4733
+ `policy` is the Content-Security-Policy; a project page opened in its own tab runs sandboxed (PAGE_POLICY).
4734
+ """
4607
4735
  size = path.stat().st_size if data is None else len(data)
4608
4736
  start, end, status = 0, size - 1, 200
4609
4737
  match = re.fullmatch(r"bytes=(\d*)-(\d*)", self.headers.get("Range", "").strip())
@@ -4629,7 +4757,7 @@ class DiscussionHandler(BaseHTTPRequestHandler):
4629
4757
  for name, value in (extra or {}).items():
4630
4758
  self.send_header(name, value)
4631
4759
  self.send_header("X-Content-Type-Options", "nosniff")
4632
- self.send_header("Content-Security-Policy", "default-src 'none'; sandbox")
4760
+ self.send_header("Content-Security-Policy", policy)
4633
4761
  self.send_header("Cache-Control", "no-store")
4634
4762
  self.send_header("Referrer-Policy", "no-referrer")
4635
4763
  self.end_headers()
@@ -40,8 +40,8 @@ Use “History” to bring context from an existing local AI conversation into a
40
40
  ## Change a model, name, or private prompt
41
41
 
42
42
  - **Model and reasoning effort.** Set these on the back of a member card when creating a room or inviting a member. In an existing room, open **Room → Members and settings** in the tabs at the top of the room and find the member. Change the model or effort, or refresh the model list. Changes take effect on the next run. For app connections, choose the model and effort in the app itself. Where supported, you can switch between CLI and app connections here. A manually connected member that is now woken by this computer shows “Existing session” next to its connection. It keeps its original session’s project access, but you can still change its model and effort here. While its own window is open, tasks go straight into that window and run with the window’s model; this setting applies once the window is closed. Until a change has been used, the model field shows the model that last ran followed by “(set to …, applies from the next run)” or “(set to …, applies once its own window is closed)”.
43
- - **Display name and role description.** Open the member menu in the right sidebar and select “Name and description”. When adding a member, use the name and description button on the card. On cards that flip, these settings are on the back. Change the room display name and role description. Inside a room there are quicker ways: double-click a member’s name in the right sidebar or on the members and settings page to rename it in place (Enter or clicking elsewhere saves, Esc cancels). Member rows in the right sidebar do not show descriptions: point at a member with the mouse and its member card floats out on the left with the description and an “Edit name and description” button. In the editor, click a common kind of work to add it. The host and smart scheduling use the description to route work. You can also save it as the app’s default description.
44
- - **Private prompt.** When creating a room or inviting, flip the member card and select “Expert prompt” on its back. For a member already in the room, point at it in the right sidebar and select “Expert prompt” on the member card that floats out. Write instructions for this member alone, such as “Start with the conclusion”; they apply from its next wake-up. This does not change its permissions. A member from a workflow shows its prompt read-only; change it in the workflow. Manually started and external members have no private prompt.
43
+ - **Display name and role description.** Open the member menu in the right sidebar and select “Name and description”. When adding a member, use the name and description button on the card. On cards that flip, these settings are on the back. Change the room display name and role description. Inside a room there are quicker ways: double-click a member’s name in the right sidebar or on the members and settings page to rename it in place (Enter or clicking elsewhere saves, Esc cancels). Member rows in the right sidebar do not show descriptions: point at a member with the mouse and its member card floats out on the left with the description and an “Edit name and description” button; on a phone or tablet, tap the member row and the menu that opens shows the description at the top. In the editor, click a common kind of work to add it. The host and smart scheduling use the description to route work. You can also save it as the app’s default description.
44
+ - **Private prompt.** When creating a room or inviting, flip the member card and select “Expert prompt” on its back. For a member already in the room, point at it in the right sidebar and select “Expert prompt” on the member card that floats out; on a phone or tablet, tap the member row and choose “Expert prompt” in the menu. Write instructions for this member alone, such as “Start with the conclusion”; they apply from its next wake-up. This does not change its permissions. A member from a workflow shows its prompt read-only; change it in the workflow. Manually started and external members have no private prompt.
45
45
  - **System prompts for all members or one platform.** In **Settings → System prompts**, the “All members” row goes to every member this computer wakes, and each platform row (Claude, Codex, Gemini, DeepSeek and so on) goes to every member on that platform, including preset and workflow experts. They come before the private prompt and apply from the next wake-up. The software’s own CLAUDE.md and AGENTS.md are not changed, so using that software outside CoDiscuss is not affected. From the command line, use `codiscuss launch prompts`.
46
46
 
47
47
  ## Set the host, pause participation, invite back, or remove