ai_co_discuss 0.2.41 → 0.2.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/admin.py +186 -0
- package/backend/schema.sql +670 -655
- package/backend/server.py +53 -1
- package/docs/architecture.md +4 -1
- package/docs/deployment.md +4 -0
- package/package.json +1 -1
- package/web/app.js +171 -9
- package/web/modern.css +1 -1
- package/web/modern.js +720 -431
package/backend/server.py
CHANGED
|
@@ -7,6 +7,7 @@ import json
|
|
|
7
7
|
import logging
|
|
8
8
|
import os
|
|
9
9
|
import re
|
|
10
|
+
import secrets
|
|
10
11
|
import socket
|
|
11
12
|
import sqlite3
|
|
12
13
|
import subprocess
|
|
@@ -19,6 +20,7 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
19
20
|
from pathlib import Path
|
|
20
21
|
from urllib.parse import parse_qs, quote, urlsplit
|
|
21
22
|
|
|
23
|
+
from .admin import AdminError, admin_status, login_admin, logout_admin, register_admin, session_valid, update_profile
|
|
22
24
|
from .free_room import (add_member, after_free_message, authorize_free_write, check_answer, check_proxy, execution_action, free_view,
|
|
23
25
|
inbox, interrupt_member, member_action, member_values, migrate_free_tables, proxy_member, reserve_execution,
|
|
24
26
|
discussion_members, room_mode, save_room_access, sync_discussion_members, view_execution)
|
|
@@ -42,6 +44,7 @@ MAX_FILENAME_LENGTH = 255
|
|
|
42
44
|
LOCAL_LAUNCH_TIMEOUT = 60
|
|
43
45
|
# Ordering and filing a channel only rearrange the shared directory, like folder edits, so they need no room credential.
|
|
44
46
|
DIRECTORY_OPERATIONS = ("move", "folder")
|
|
47
|
+
ADMIN_OPERATIONS = ("archive", "restore", "delete")
|
|
45
48
|
DIRECTORY_PICKER_TIMEOUT = 600 # the folder dialog waits for the person at the computer
|
|
46
49
|
MAX_TEXT_LENGTH = 32000
|
|
47
50
|
SESSION_ID_PATTERN = re.compile(r"[0-9A-Za-z_-]{8,128}")
|
|
@@ -1340,6 +1343,8 @@ class DiscussionServer(ThreadingHTTPServer):
|
|
|
1340
1343
|
if local_launch and address[0] != "127.0.0.1":
|
|
1341
1344
|
raise ValueError("本机启动入口须绑定 127.0.0.1")
|
|
1342
1345
|
self.local_launch = local_launch
|
|
1346
|
+
self.local_site = address[0] in ("127.0.0.1", "::1", "localhost")
|
|
1347
|
+
self.admin_setup_key = os.getenv("DISCUSS_ADMIN_SETUP_KEY") or secrets.token_urlsafe(18)
|
|
1343
1348
|
service_home = os.getenv("DISCUSS_SERVICE_HOME")
|
|
1344
1349
|
self.connections_file = Path(service_home) / "site-connections.json" if service_home else None
|
|
1345
1350
|
super().__init__(address, DiscussionHandler)
|
|
@@ -1432,6 +1437,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
1432
1437
|
if text_mode and method == "GET":
|
|
1433
1438
|
return self.handle_text(connection, parts, params)
|
|
1434
1439
|
return self.handle_api(connection, parts, params, method)
|
|
1440
|
+
except AdminError as error:
|
|
1441
|
+
return self.respond({"error": str(error)}, error.status)
|
|
1435
1442
|
except PermissionError as error:
|
|
1436
1443
|
return self.respond({"error": str(error)}, 403)
|
|
1437
1444
|
except (ValueError, TypeError) as error:
|
|
@@ -1608,10 +1615,43 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
1608
1615
|
return self.respond(failure, 400)
|
|
1609
1616
|
return self.respond(json.loads(result.stdout))
|
|
1610
1617
|
|
|
1618
|
+
def admin_token(self):
|
|
1619
|
+
"""The administrator session token supplied by the browser."""
|
|
1620
|
+
return self.headers.get("X-Discussion-Admin", "")
|
|
1621
|
+
|
|
1622
|
+
def admin_session(self, connection):
|
|
1623
|
+
"""Whether the request is from the administrator: any visitor of a loopback-only site, else a valid session."""
|
|
1624
|
+
return self.server.local_site or session_valid(connection, self.admin_token())
|
|
1625
|
+
|
|
1626
|
+
def handle_admin_api(self, connection, parts, method):
|
|
1627
|
+
"""Serve administrator registration, login sessions and profile."""
|
|
1628
|
+
token = self.admin_token()
|
|
1629
|
+
if parts == ["api", "admin"] and method == "GET":
|
|
1630
|
+
result = admin_status(connection, token, True, self.server.local_site)
|
|
1631
|
+
connection.commit()
|
|
1632
|
+
return self.respond(result)
|
|
1633
|
+
if len(parts) != 3 or method != "POST":
|
|
1634
|
+
raise LookupError("地址不存在")
|
|
1635
|
+
payload = self.read_payload()
|
|
1636
|
+
now = int(time.time())
|
|
1637
|
+
if self.server.local_site and parts[2] != "profile":
|
|
1638
|
+
raise ValueError("本地站点无需管理员账号")
|
|
1639
|
+
actions = {"register": lambda: register_admin(connection, payload, self.server.admin_setup_key, now),
|
|
1640
|
+
"login": lambda: login_admin(connection, payload, now),
|
|
1641
|
+
"logout": lambda: logout_admin(connection, token),
|
|
1642
|
+
"profile": lambda: update_profile(connection, token, payload, self.server.local_site)}
|
|
1643
|
+
if parts[2] not in actions:
|
|
1644
|
+
raise LookupError("地址不存在")
|
|
1645
|
+
result = actions[parts[2]]()
|
|
1646
|
+
connection.commit()
|
|
1647
|
+
return self.respond(result, 201 if parts[2] == "register" else 200)
|
|
1648
|
+
|
|
1611
1649
|
def handle_api(self, connection, parts, params, method):
|
|
1612
1650
|
"""Handle room, state, and message operations used by the web UI."""
|
|
1613
1651
|
if parts == ["api", "health"] and method == "GET":
|
|
1614
1652
|
return self.respond({"ok": True})
|
|
1653
|
+
if parts[:2] == ["api", "admin"]:
|
|
1654
|
+
return self.handle_admin_api(connection, parts, method)
|
|
1615
1655
|
if parts == ["api", "rooms"]:
|
|
1616
1656
|
if method == "GET":
|
|
1617
1657
|
return self.respond({**list_rooms(connection, params), "participants": PARTICIPANTS})
|
|
@@ -1672,7 +1712,8 @@ class DiscussionHandler(BaseHTTPRequestHandler):
|
|
|
1672
1712
|
raise ValueError("自由房间不使用讨论运行控制")
|
|
1673
1713
|
return self.handle_runtime_api(connection, parts, params, method)
|
|
1674
1714
|
free_actor = None
|
|
1675
|
-
if method == "POST" and len(parts) == 4 and parts[3] in DIRECTORY_OPERATIONS
|
|
1715
|
+
if method == "POST" and len(parts) == 4 and (parts[3] in DIRECTORY_OPERATIONS
|
|
1716
|
+
or parts[3] in ADMIN_OPERATIONS and self.admin_session(connection)):
|
|
1676
1717
|
pass
|
|
1677
1718
|
elif method == "POST" and free:
|
|
1678
1719
|
free_actor = authorize_free_write(connection, room_id, token, parts[3] if len(parts) > 3 else "", self.read_payload())
|
|
@@ -1894,11 +1935,22 @@ def main():
|
|
|
1894
1935
|
parser.add_argument("--database", default=os.getenv("DATABASE_PATH", str(ROOT / "data" / "discuss.sqlite3")))
|
|
1895
1936
|
parser.add_argument("--no-demo", action="store_true", help="Do not seed sample data in a new database")
|
|
1896
1937
|
parser.add_argument("--local-launch", action="store_true", help="Enable local AI launch and configuration (127.0.0.1 only)")
|
|
1938
|
+
parser.add_argument("--reset-admin", action="store_true", help="Delete the administrator account and sessions, then exit")
|
|
1897
1939
|
args = parser.parse_args()
|
|
1898
1940
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s")
|
|
1899
1941
|
init_database(args.database, seed=not args.no_demo)
|
|
1942
|
+
if args.reset_admin:
|
|
1943
|
+
with closing(connect_db(args.database)) as connection, connection:
|
|
1944
|
+
connection.execute("DELETE FROM admin_sessions")
|
|
1945
|
+
connection.execute("DELETE FROM site_admin")
|
|
1946
|
+
logging.info("管理员账号已清除;再次打开网站时可用安装令牌重新注册")
|
|
1947
|
+
return
|
|
1900
1948
|
server = DiscussionServer((args.host, args.port), args.database, local_launch=args.local_launch)
|
|
1901
1949
|
logging.info("AI CoDiscuss ready at http://%s:%s", args.host, args.port)
|
|
1950
|
+
with closing(connect_db(args.database)) as connection:
|
|
1951
|
+
if not server.local_site and connection.execute("SELECT 1 FROM site_admin").fetchone() is None:
|
|
1952
|
+
logging.info("尚未注册管理员账号;注册所需安装令牌:%s",
|
|
1953
|
+
"见环境变量 DISCUSS_ADMIN_SETUP_KEY" if os.getenv("DISCUSS_ADMIN_SETUP_KEY") else server.admin_setup_key)
|
|
1902
1954
|
try:
|
|
1903
1955
|
server.serve_forever()
|
|
1904
1956
|
except KeyboardInterrupt:
|
package/docs/architecture.md
CHANGED
|
@@ -153,6 +153,7 @@ Python 在一个只读事务快照中查询;D1 使用同一个 batch 事务读
|
|
|
153
153
|
| `CreateDiscussion.vue`、`LimitPicker.vue`、`LaunchSettings.vue` | 新建讨论表单及本机启动配置;推进方式与参与专家分组,单选方式使用强调色卡片,参与者通过“邀请 AI”加入并独立移出;轮次和时长独立配置,以“不限”按钮切换各自上限,按需展开滚轮,选择即时生效,并预览到限条件;鼠标滚轮逐格切换且不产生惯性,鼠标及触摸拖动松手后保留惯性,先阻尼滑行再吸附预计停点,轻点中间数字精确输入;键盘聚焦和直接输入时仅高亮中间选中行,输入与显示共用行高,避免整列描边与原生输入框叠加;时长分小时/分钟两列,收起与摘要共用时长格式;支持键盘,减少动态效果时保留拖动惯性并去掉三维翻转 |
|
|
154
154
|
| `ProgressBoard.vue`、`ProgressPanel.vue` | 共享进度看板及抽屉容器;Codex 参与者菜单内直接打开 App / CLI 切换弹窗,显式暂停后复用本场配置的读取与保存,不跳转接入页或自动重启 |
|
|
155
155
|
| `FreeBoard.vue` | 自由协作房间的右侧看板,版式与讨论进度看板一致:房间状态与请求/执行计数、当前任务、成员(主持人居首,显示接入方式、模型与状态)、邀请、发起头脑风暴和每次执行用时 |
|
|
156
|
+
| `AccountSettings.vue` | 设置弹窗的管理员账号分区(注册、登录、改名与头像、退出登录) |
|
|
156
157
|
| `use-discussion.js` | 将 `web/app.js` 的共享控制器状态接入 Vue |
|
|
157
158
|
| `theme.css`、`channel.css` | 组件主题、深浅配色与响应式布局 |
|
|
158
159
|
| `markdown.mjs`、`markdown.css`、`backup.mjs` | 三个主题共用的内容渲染与本地导出 |
|
|
@@ -195,6 +196,8 @@ Python 在一个只读事务快照中查询;D1 使用同一个 batch 事务读
|
|
|
195
196
|
|
|
196
197
|
等待提示文字使用局部明暗流光,文字与卡片位置保持稳定,深浅主题继承原有文字颜色。流光采用 Feel 的 `calm, smooth` 参数(质量 1、刚度 78.167、阻尼 18.567),以恒定驱动力 `k / 8` 与阻尼的解析解推进;循环衔接时亮带完全位于文字之外,不使用固定动画时长。每帧只更新文字的 CSS 变量,不触发消息流重绘;卡片移除或开启“减少动态效果”时取消帧循环并恢复普通文字。
|
|
197
198
|
|
|
199
|
+
管理员账号界面:页面启动及标签页重新可见时读取公开的 `GET /api/admin`,用返回的名称和头像覆盖「用户」身份(所有访客可见,无自定义时仍是 User 与指纹图标),登录、注册、退出、改资料后直接更新身份与快照,不刷新页面。会话令牌只存浏览器 `localStorage` 的 `discuss-admin-session`,由控制器附加到写请求的 `X-Discussion-Admin`,不进入视图快照;会话不过期,前端仅在服务端判定未登录时清除本地令牌。左下角用户块可点击打开「设置」:未注册显示“设置管理员账号”并给出注册表单(安装令牌来源提示;服务端未配置时说明并禁止提交),已注册未登录显示“未登录 · 点击登录”,已登录显示名称、头像(居中裁成 96×96 JPEG 数据 URL,超过 60000 字符则提示过大)、恢复默认头像与退出登录;忘记密码时本地版运行 `python server.py --reset-admin` 后重新注册,Cloudflare 版需清空管理员表。表单校验与服务端规则一致,错误行内展示服务端中文原文。本地站点(`GET /api/admin` 返回 `local: true`)不需要账号:不显示注册、登录、退出,不发送也不保存会话令牌,设置里只保留名称与头像编辑,左下角只显示网站连接状态。没有房间控制凭据且未登录时,存档、恢复、删除被拒会提示“需要登录管理员账号或使用创建该房间的浏览器”。
|
|
200
|
+
|
|
198
201
|
### 网页实时更新
|
|
199
202
|
|
|
200
203
|
浏览器通过 `GET /api/updates` 订阅 SSE。房间、消息、主持安排、运行状态及目录的成功写入提交后发送 `change`,只含空对象,不携带正文、身份或执行凭据;普通执行续租不通知。页面在 100ms 内合并连续通知,复用已有接口读取当前房间和目录,消息仍按最后编号增量读取;请求期间的新通知会再触发一次读取,拖动目录时延后处理。筛选、未发送草稿和原有滚动跟随规则保留。
|
|
@@ -247,7 +250,7 @@ running 状态即使只有 pending 事件,也必须先暂停才能重新启动
|
|
|
247
250
|
|
|
248
251
|
自由房间(`room_modes.mode='free'`)与讨论房间共用房间、成员登记、消息、附件与目录,没有发言权、安排、阶段推进和轮次。没有控制凭据登记的旧房间只供阅读,不支持通过首次运行配置认领;本次不迁移历史房间。
|
|
249
252
|
|
|
250
|
-
-
|
|
253
|
+
- **凭据**:建房时由客户端提供房间控制凭据和每位成员的成员凭证,服务端只存哈希。用户身份的房间写入(发言、附件、存档、恢复、删除、打断)都须控制凭据(存档、恢复、删除也可凭管理员会话);房间排序和归入文件夹只改共享目录,与站点级文件夹操作一样不需要凭据;无凭据、错误凭据、成员凭证或他房凭据一律只读。**站点管理员**:绑定 127.0.0.1 的本地站点没有账号,访问者即管理员(存档、恢复、删除免凭据,名称与头像存在 `site_admin`,密码哈希为不可登录的占位值);其余部署需要账号:单个账号(`site_admin`,用户名+PBKDF2 密码哈希,会话令牌只存哈希于 `admin_sessions`,登录后一直有效直至退出)。首次注册须提供安装令牌(本地版读 `DISCUSS_ADMIN_SETUP_KEY`,未设置则启动时随机生成并写日志;Worker 读机密 `ADMIN_SETUP_KEY`,未配置则不能注册);连续 5 次登录失败锁定 5 分钟。请求头 `X-Discussion-Admin` 携带有效会话时,存档、恢复、永久删除(仍须确认房间名)免房间凭据;其余写入不变。`GET /api/admin` 公开,返回名称与头像供所有访客显示。接口为 `/api/admin` 下的 `register`、`login`、`logout`、`profile`。忘记密码:本地版 `python server.py --reset-admin`,Cloudflare 版执行 `DELETE FROM admin_sessions; DELETE FROM site_admin;`,之后重新注册。成员凭证只能以该成员身份发言或上传附件。声明字段(`author`、`source`、localhost)不代替凭据。
|
|
251
254
|
- **成员**:`room_members` 以 `id` 为稳定主键,`access` 为 `runner`(接入程序投递)、`manual`(成员自行读写)或 `online`(只读、原文代发),`session_mode` 标记是否借用用户正在使用的会话。房主用控制凭据 `POST members` 运行中加入成员,`POST members/ID {action}` 让成员离开(`away`,作废其进行中执行与未投递请求)、请回(`active`,必须提供不同于原凭证的新凭证,旧凭证副本不再有效)或移除(`remove`,保留历史发言)。同一成员凭证不能复用于其他成员或房主;相同凭证与配置的邀请、请回重试返回已有结果。会话续接由本机接入程序负责,服务端不保存会话绑定;唯一例外是手动成员上报的会话:带凭据的请求可带请求头 `X-Discussion-Session` 与 `X-Discussion-Session-Client`,`message post` 也可在正文带 `session_id` 与 `session_client`(CLI 读取 `CLAUDE_CODE_SESSION_ID` 或 `CODEX_THREAD_ID`,取值 `claude` / `codex`),服务端在 `member_sessions` 保存该手动成员最近上报的会话,成员视图以 `reported_session` 暴露。房主用 `POST members/ID {action:"adopt", adapter:"claude", session_id}`(须与上报一致、仅全自动讨论中在场的手动成员)把成员改为 `runner`、`borrowed` 并清除上报,本机接入程序据此接管。两套后端行为一致。
|
|
252
255
|
- **手动成员注册**:`member_registrations`(`member_id`、`room_id`、`token_hash`、`registered_at`)记录手动成员自己发起的注册,`POST /api/rooms/ID/register` 只接受该成员自己的凭证(房主凭据与他人凭证返回 403),重复调用保留首次时间。记录绑定注册时的凭证哈希:请回换发新凭证后旧记录不再匹配,视图中的 `registered_at` 回到空串,须重新注册。会话 ID 不属于注册内容,仍由 CLI 头部采集进 `member_sessions`;`adopt` 要求已注册。讨论房间的成员视图与自由房间 `free.members` 都带 `registered_at`;新表为独立表,D1 重新应用 schema 即可。
|
|
253
256
|
- **请求**:用户消息按结构化接收者 `to`(成员名)为每位成员生成一条请求;省略且仅有一位在场成员时默认点名该成员,多位成员时交给主持人(`route`),只有在线成员而没有主持人时只作留言,不广播。网页只从正文中代码与引用之外的 `@成员` 生成 `to`,没有 @ 时省略 `to`。请求状态为 `pending`(待投递)→ `delivering`(处理中)→ `completed` / `cancelled` / `failed`。
|
package/docs/deployment.md
CHANGED
|
@@ -26,6 +26,8 @@ python server.py --host 127.0.0.1 --port 8765 --no-demo
|
|
|
26
26
|
|
|
27
27
|
命令行参数优先于环境变量。使用独立测试库可加 `--database data/test.sqlite3`。停止后重新启动沿用原库;`--no-demo` 不清理已有数据。长期部署应使用自己的进程管理和反向代理提供 HTTPS,按需要限制访问与请求规模。
|
|
28
28
|
|
|
29
|
+
管理员账号:绑定 127.0.0.1 时无需账号,访问者即管理员,可存档、恢复、永久删除任意房间。绑定其他地址(如 `--host 0.0.0.0`)时须注册:首次打开网站在左下角注册,需要安装令牌。环境变量 `DISCUSS_ADMIN_SETUP_KEY` 可固定令牌,未设置时每次启动随机生成并写入启动日志(仅在尚未注册时打印)。注册后可存档、恢复、永久删除任意房间;忘记密码运行 `python server.py --reset-admin`(不停服务也可执行)后重新注册。
|
|
30
|
+
|
|
29
31
|
网页 SSE 推送在 Python 服务中默认启用,无需额外进程或数据库迁移。反向代理应关闭 `/api/updates` 的响应缓冲并允许长连接;服务每 15 秒发送心跳。页面隐藏时断开,重新打开后补取最新数据;代理不支持推送时回退轮询。
|
|
30
32
|
|
|
31
33
|
附件保存在数据库旁的 `<数据库文件名>.attachments/`,例如 `data/discuss.sqlite3.attachments/`;Docker 中同样位于数据卷内。备份时先停止对应写入进程,再一并复制数据库和附件目录;只备份 SQLite 不包含原文件。无附件时也可用 SQLite 的在线备份工具生成一致快照,不要仅复制正在写入的主文件而遗漏 WAL。恢复前保留原库和附件目录,再用 `--database` 指向恢复副本核验。
|
|
@@ -118,6 +120,8 @@ npx wrangler d1 execute DB --remote --config .wrangler/deploy/wrangler.jsonc --f
|
|
|
118
120
|
npm run deploy -- --cwd .wrangler/deploy
|
|
119
121
|
```
|
|
120
122
|
|
|
123
|
+
管理员注册:Cloudflare 站点须先设置安装令牌机密,未设置则无法注册管理员:`npx wrangler pages secret put ADMIN_SETUP_KEY --project-name YOUR_PROJECT_NAME`。忘记密码时在 D1 执行 `DELETE FROM admin_sessions; DELETE FROM site_admin;` 后重新注册。
|
|
124
|
+
|
|
121
125
|
第一次对新库执行 schema;升级已有站点前先备份并在本地副本核验迁移。当前 schema 以增量表、索引和触发器扩展数据结构,重复执行不应清空已有记录或重置发言权;仍需按实际升级版本测试。
|
|
122
126
|
|
|
123
127
|
`deploy` 会先构建,再将 `dist/pages/` 发布到 `main`。配置为真值前不要直接运行根目录默认部署。构建本身不发布、不改远端数据库。Git 集成部署需自行将实际 D1 配置提供给构建环境,不能直接用公开模板当作生产配置。
|
package/package.json
CHANGED
package/web/app.js
CHANGED
|
@@ -17,12 +17,22 @@ const DIRECTORY_DRAG_OFFSET = 12;
|
|
|
17
17
|
const THEME_STORAGE_KEY = "ai-codiscuss-theme";
|
|
18
18
|
const DIRECTORY_SORT_KEY = "ai-codiscuss-directory-sort";
|
|
19
19
|
const LAUNCH_PENDING_PREFIX = "discuss-launch:";
|
|
20
|
+
const ADMIN_SESSION_KEY = "discuss-admin-session";
|
|
21
|
+
const ADMIN_USERNAME_MAX = 30;
|
|
22
|
+
const ADMIN_PASSWORD_MIN = 8;
|
|
23
|
+
const ADMIN_PASSWORD_MAX = 128;
|
|
24
|
+
const ADMIN_AVATAR_MAX_CHARS = 60000;
|
|
25
|
+
const ADMIN_AVATAR_SIZE = 96;
|
|
26
|
+
const ADMIN_AVATAR_QUALITY = 0.8;
|
|
20
27
|
const MEMBER_ACCESS_PREFIX = "discuss-members:";
|
|
21
28
|
const MEMBER_PENDING_PREFIX = "discuss-member-pending:";
|
|
22
29
|
const LOCAL_CONNECTION_KEY = "discuss-local-connection";
|
|
23
30
|
const LOCAL_CONNECTION_TIMEOUT_MS = 15000;
|
|
24
31
|
const MODEL_CATALOG_TIMEOUT_MS = 35000;
|
|
25
32
|
let local_connection = null;
|
|
33
|
+
const DEFAULT_USER_LABEL = "User";
|
|
34
|
+
const DEFAULT_USER_ICON = "/icons/user.svg";
|
|
35
|
+
const MANAGEMENT_LOGIN_HINT = "需要登录管理员账号或使用创建该房间的浏览器";
|
|
26
36
|
const THEMES = ["channel", "channel-light"];
|
|
27
37
|
const SOURCE_LABELS = { demo: "示例", user: "本人发言", proxy: "用户代发", cli: "CLI 发言", api: "API 发言", url: "历史 URL 发言", host_proxy: "主持人代发" };
|
|
28
38
|
const PHASE_LABELS = { preparing: "准备中", initial: "独立观点", discussing: "深入讨论", reviewing: "结论复核", paused: "已暂停", concluded: "已收束" };
|
|
@@ -60,6 +70,7 @@ state.directory_notice = "";
|
|
|
60
70
|
state.directory_pending = new Map();
|
|
61
71
|
state.directory_version = 0;
|
|
62
72
|
state.navigation_version = 0;
|
|
73
|
+
state.admin = { loaded: false, local: false, registered: false, setup_available: false, logged_in: false, profile: null, identity_version: 0 };
|
|
63
74
|
state.launch = { available: false, remote: false, connect_command: "", profiles: {}, workspace: {}, scheduler: {}, create: true, error: "", notice: "", recoveries: [] };
|
|
64
75
|
const PLATFORM_CLIENTS = { Codex: [{ value: "codex_cli", label: "Codex CLI" }, { value: "codex", label: "Codex App" }],
|
|
65
76
|
Claude: [{ value: "claude", label: "Claude Code CLI" }],
|
|
@@ -125,12 +136,31 @@ function show_toast(message, is_error = false) {
|
|
|
125
136
|
state.toast_timer = setTimeout(() => { element("toast").hidden = true; }, TOAST_DURATION_MS);
|
|
126
137
|
}
|
|
127
138
|
|
|
139
|
+
/** The administrator session token kept by this browser, or an empty string. */
|
|
140
|
+
function admin_token() {
|
|
141
|
+
if (state.admin.local) return "";
|
|
142
|
+
try { return localStorage.getItem(ADMIN_SESSION_KEY) || ""; } catch { return ""; }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Store or clear the administrator session token; storage failures only lose persistence. */
|
|
146
|
+
function store_admin_token(token) {
|
|
147
|
+
try { token ? localStorage.setItem(ADMIN_SESSION_KEY, token) : localStorage.removeItem(ADMIN_SESSION_KEY); } catch { /* Keep the session in memory only. */ }
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The administrator header for writes that bypass request_json, or no header without a session. */
|
|
151
|
+
function admin_headers() {
|
|
152
|
+
const session = admin_token();
|
|
153
|
+
return session ? { "X-Discussion-Admin": session } : {};
|
|
154
|
+
}
|
|
155
|
+
|
|
128
156
|
/** Request JSON from the local or remotely hosted discussion service. */
|
|
129
157
|
async function request_json(path, payload, access_token) {
|
|
130
158
|
const options = { cache: "no-store" };
|
|
131
159
|
const target_room = path.match(/^\/api\/rooms\/([^/?]+)/)?.[1];
|
|
132
160
|
const token = access_token || (target_room ? localStorage.getItem(`discuss-access:${target_room}`) : null);
|
|
161
|
+
const session = admin_token();
|
|
133
162
|
options.headers = token ? { "X-Discussion-Token": token } : {};
|
|
163
|
+
if (session) options.headers["X-Discussion-Admin"] = session;
|
|
134
164
|
if (payload !== undefined) {
|
|
135
165
|
options.method = "POST";
|
|
136
166
|
options.headers["Content-Type"] = "application/json";
|
|
@@ -138,10 +168,127 @@ async function request_json(path, payload, access_token) {
|
|
|
138
168
|
}
|
|
139
169
|
const response = await fetch(path, options);
|
|
140
170
|
const result = await response.json();
|
|
141
|
-
if (!response.ok) throw Object.assign(new Error(result.error || "请求失败,请重试"), { preflight: response.status >= 400 && response.status < 500 });
|
|
171
|
+
if (!response.ok) throw Object.assign(new Error(result.error || "请求失败,请重试"), { preflight: response.status >= 400 && response.status < 500, status: response.status });
|
|
142
172
|
return result;
|
|
143
173
|
}
|
|
144
174
|
|
|
175
|
+
/** The owner's public name and avatar replace the default "User" identity for every visitor. */
|
|
176
|
+
function apply_admin_identity(profile) {
|
|
177
|
+
Object.assign(PLATFORM_IDENTITIES["用户"], { label: profile?.username || DEFAULT_USER_LABEL, icon: profile?.avatar || DEFAULT_USER_ICON });
|
|
178
|
+
state.admin.identity_version++;
|
|
179
|
+
if (!element("participants")) return;
|
|
180
|
+
for (const id of ["author-select", "topic-host-select", "new-room-host"]) {
|
|
181
|
+
const option = Array.from(element(id)?.options || []).find(item => item.value === "用户");
|
|
182
|
+
if (option) option.textContent = display_name("用户");
|
|
183
|
+
}
|
|
184
|
+
render_participants();
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Record the server's administrator state and refresh every identity-dependent view without a reload. */
|
|
188
|
+
function apply_admin_state(info) {
|
|
189
|
+
const local = info.local === true;
|
|
190
|
+
if (local || !info.logged_in) store_admin_token("");
|
|
191
|
+
Object.assign(state.admin, { loaded: true, local, registered: Boolean(info.registered), setup_available: Boolean(info.setup_available),
|
|
192
|
+
logged_in: Boolean(info.logged_in), profile: info.profile ? { username: info.profile.username, avatar: info.profile.avatar || "" } : null });
|
|
193
|
+
apply_admin_identity(state.admin.profile);
|
|
194
|
+
publish_view();
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Read the public administrator state; a failure leaves the visitor view unchanged. */
|
|
198
|
+
async function load_admin_state() {
|
|
199
|
+
try { apply_admin_state(await request_json("/api/admin")); }
|
|
200
|
+
catch { /* The directory request reports connection problems. */ }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Return the first problem with an administrator form, matching the server's limits. */
|
|
204
|
+
function validate_admin_form({ username, password, confirm, check_password = true }) {
|
|
205
|
+
const name_length = [...String(username ?? "").trim()].length;
|
|
206
|
+
if (username !== undefined && (name_length < 1 || name_length > ADMIN_USERNAME_MAX)) return `用户名需要 1–${ADMIN_USERNAME_MAX} 个字符`;
|
|
207
|
+
if (!check_password) return "";
|
|
208
|
+
const length = [...String(password ?? "")].length;
|
|
209
|
+
if (length < ADMIN_PASSWORD_MIN || length > ADMIN_PASSWORD_MAX) return `密码需要 ${ADMIN_PASSWORD_MIN}–${ADMIN_PASSWORD_MAX} 个字符`;
|
|
210
|
+
if (confirm !== undefined && confirm !== password) return "两次输入的密码不一致";
|
|
211
|
+
return "";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Keep the Chinese server message and add a retry hint when a locked response lacks the delay. */
|
|
215
|
+
function admin_error(error) {
|
|
216
|
+
if (error.status === 429 && !/\d/.test(error.message)) error.message += ",请稍后再试";
|
|
217
|
+
return error;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Store the new session and show the owner's identity. */
|
|
221
|
+
function accept_admin_session({ token, profile }) {
|
|
222
|
+
store_admin_token(token);
|
|
223
|
+
apply_admin_state({ registered: true, setup_available: false, logged_in: true, profile });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Create the single administrator account and sign in with it. */
|
|
227
|
+
async function register_admin({ username, password, confirm, setup_key }) {
|
|
228
|
+
const problem = validate_admin_form({ username, password, confirm }) || (String(setup_key ?? "").trim() ? "" : "请填写安装令牌");
|
|
229
|
+
if (problem) throw new Error(problem);
|
|
230
|
+
try { accept_admin_session(await request_json("/api/admin/register", { username: username.trim(), password, setup_key: setup_key.trim() })); }
|
|
231
|
+
catch (error) { throw admin_error(error); }
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Sign in and keep the session in this browser. */
|
|
235
|
+
async function login_admin({ username, password }) {
|
|
236
|
+
if (!String(username ?? "").trim() || !password) throw new Error("请填写用户名和密码");
|
|
237
|
+
try { accept_admin_session(await request_json("/api/admin/login", { username: username.trim(), password })); }
|
|
238
|
+
catch (error) { throw admin_error(error); }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Leave this browser; the local session is dropped even if the server cannot be reached. */
|
|
242
|
+
async function logout_admin() {
|
|
243
|
+
try { await request_json("/api/admin/logout", {}); }
|
|
244
|
+
catch { /* The token is removed below either way. */ }
|
|
245
|
+
store_admin_token("");
|
|
246
|
+
state.admin.logged_in = false;
|
|
247
|
+
publish_view();
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Save the display name and/or avatar; an empty avatar restores the default. */
|
|
251
|
+
async function update_admin_profile(patch) {
|
|
252
|
+
if (patch.username !== undefined) {
|
|
253
|
+
const problem = validate_admin_form({ username: patch.username, check_password: false });
|
|
254
|
+
if (problem) throw new Error(problem);
|
|
255
|
+
patch = { ...patch, username: patch.username.trim() };
|
|
256
|
+
}
|
|
257
|
+
const result = await request_json("/api/admin/profile", patch);
|
|
258
|
+
apply_admin_state({ local: state.admin.local, registered: true, setup_available: false, logged_in: true, profile: result.profile });
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Shrink the chosen image into a small square data URL that fits the server limit. */
|
|
262
|
+
async function admin_avatar_from_file(file) {
|
|
263
|
+
if (!file?.type?.startsWith("image/")) throw new Error("请选择图片文件");
|
|
264
|
+
const url = URL.createObjectURL(file);
|
|
265
|
+
try {
|
|
266
|
+
const image = await new Promise((resolve, reject) => {
|
|
267
|
+
const loaded = new Image();
|
|
268
|
+
loaded.onload = () => resolve(loaded);
|
|
269
|
+
loaded.onerror = () => reject(new Error("无法读取这张图片"));
|
|
270
|
+
loaded.src = url;
|
|
271
|
+
});
|
|
272
|
+
const side = Math.min(image.naturalWidth, image.naturalHeight);
|
|
273
|
+
if (!side) throw new Error("无法读取这张图片");
|
|
274
|
+
const canvas = document.createElement("canvas");
|
|
275
|
+
canvas.width = canvas.height = ADMIN_AVATAR_SIZE;
|
|
276
|
+
const context = canvas.getContext("2d");
|
|
277
|
+
context.fillStyle = "#ffffff";
|
|
278
|
+
context.fillRect(0, 0, ADMIN_AVATAR_SIZE, ADMIN_AVATAR_SIZE);
|
|
279
|
+
context.drawImage(image, (image.naturalWidth - side) / 2, (image.naturalHeight - side) / 2, side, side, 0, 0, ADMIN_AVATAR_SIZE, ADMIN_AVATAR_SIZE);
|
|
280
|
+
const data_url = canvas.toDataURL("image/jpeg", ADMIN_AVATAR_QUALITY);
|
|
281
|
+
if (data_url.length > ADMIN_AVATAR_MAX_CHARS) throw new Error("图片过大,请换一张");
|
|
282
|
+
return data_url;
|
|
283
|
+
} finally { URL.revokeObjectURL(url); }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** Explain why a management write failed when this browser has neither credential. */
|
|
287
|
+
function management_error_message(room_id, error) {
|
|
288
|
+
if (error.status === 403 && !state.admin.logged_in && !localStorage.getItem(`discuss-access:${room_id}`)) return MANAGEMENT_LOGIN_HINT;
|
|
289
|
+
return error.message;
|
|
290
|
+
}
|
|
291
|
+
|
|
145
292
|
/** Show connection state without claiming that any AI is online. */
|
|
146
293
|
function set_connection(connected) {
|
|
147
294
|
state.connected = connected;
|
|
@@ -179,18 +326,23 @@ function display_name(name) { return IDENTITIES[name]?.label || name; }
|
|
|
179
326
|
|
|
180
327
|
/** Render an identity avatar from a local SVG. */
|
|
181
328
|
function identity_avatar(identity) {
|
|
182
|
-
return identity.icon ? `<img src="${identity.icon}" alt="">` : identity.initials;
|
|
329
|
+
return identity.icon ? `<img src="${escape_html(identity.icon)}" alt="">` : identity.initials;
|
|
183
330
|
}
|
|
184
331
|
|
|
185
332
|
/** Render identity controls and distinguish selectable identities from connections. */
|
|
186
333
|
function render_identities() {
|
|
187
|
-
const options = Object.keys(IDENTITIES).map((name) => `<option value="${name}">${display_name(name)}</option>`).join("");
|
|
334
|
+
const options = Object.keys(IDENTITIES).map((name) => `<option value="${name}">${escape_html(display_name(name))}</option>`).join("");
|
|
188
335
|
element("author-select").innerHTML = options;
|
|
189
336
|
element("topic-host-select").innerHTML = options;
|
|
190
337
|
element("new-room-host").innerHTML = options;
|
|
191
338
|
render_expert_inputs("new-expert-modes", default_experts());
|
|
339
|
+
render_participants();
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** List the selectable identities in the classic sidebar. */
|
|
343
|
+
function render_participants() {
|
|
192
344
|
element("participants").innerHTML = Object.entries(IDENTITIES).map(([name, identity]) =>
|
|
193
|
-
`<div class="participant ${identity.style}"><span class="avatar" aria-hidden="true">${identity_avatar(identity)}</span><span class="participant-name">${display_name(name)}</span><span class="participant-role">${identity.description}</span></div>`).join("");
|
|
345
|
+
`<div class="participant ${identity.style}"><span class="avatar" aria-hidden="true">${identity_avatar(identity)}</span><span class="participant-name">${escape_html(display_name(name))}</span><span class="participant-role">${identity.description}</span></div>`).join("");
|
|
194
346
|
}
|
|
195
347
|
|
|
196
348
|
/** Render rooms while retaining the selected room. */
|
|
@@ -331,6 +483,7 @@ async function delete_channel(id) {
|
|
|
331
483
|
if (!room) return;
|
|
332
484
|
const previous = state.rooms.map(item => item.id);
|
|
333
485
|
return update_directory({ key: `delete:${id}`, label: `「${room.title}」删除`,
|
|
486
|
+
error_message: error => `「${room.title}」删除失败,已恢复原状态:${management_error_message(id, error)}`,
|
|
334
487
|
apply: () => {
|
|
335
488
|
state.rooms = state.rooms.filter(item => item.id !== id);
|
|
336
489
|
if (state.room?.id === id) run_action(() => select_room(visible_rooms()[0]?.id));
|
|
@@ -370,7 +523,7 @@ async function archive_channel(id, archived) {
|
|
|
370
523
|
const saved = await request_json(`/api/rooms/${id}/${archived ? "archive" : "restore"}`, { actor: "用户" });
|
|
371
524
|
display_channel_archive(id, { archived: Boolean(saved.archived), phase: saved.phase }, change);
|
|
372
525
|
} catch (error) {
|
|
373
|
-
state.directory_error = `「${room.title}」${archived ? "存档" : "恢复"}失败,已恢复原状态:${error
|
|
526
|
+
state.directory_error = `「${room.title}」${archived ? "存档" : "恢复"}失败,已恢复原状态:${management_error_message(id, error)}`;
|
|
374
527
|
display_channel_archive(id, previous, change);
|
|
375
528
|
throw error;
|
|
376
529
|
} finally {
|
|
@@ -1077,7 +1230,7 @@ async function upload_message_attachments(room_id, actor, drafts) {
|
|
|
1077
1230
|
const params = new URLSearchParams({ file_name: item.file.name, actor, submission_id: item.upload_submission });
|
|
1078
1231
|
const token = localStorage.getItem(`discuss-access:${room_id}`);
|
|
1079
1232
|
const response = await fetch(`/api/rooms/${room_id}/attachments?${params}`, { method: "POST",
|
|
1080
|
-
headers: { "Content-Type": "application/octet-stream", ...(token ? { "X-Discussion-Token": token } : {}) }, body: item.file });
|
|
1233
|
+
headers: { "Content-Type": "application/octet-stream", ...(token ? { "X-Discussion-Token": token } : {}), ...admin_headers() }, body: item.file });
|
|
1081
1234
|
const result = await response.json();
|
|
1082
1235
|
if (!response.ok) throw new Error(result.error || "附件上传失败");
|
|
1083
1236
|
item.uploaded = result.attachment.id;
|
|
@@ -1310,6 +1463,12 @@ function save_room_credentials(room, token, members = []) {
|
|
|
1310
1463
|
localStorage.setItem(MEMBER_ACCESS_PREFIX + room.id, JSON.stringify(saved));
|
|
1311
1464
|
}
|
|
1312
1465
|
|
|
1466
|
+
/** Public administrator state for the account UI; the session token never leaves the controller. */
|
|
1467
|
+
function admin_snapshot() {
|
|
1468
|
+
const { loaded, local, registered, setup_available, logged_in, profile, identity_version } = state.admin;
|
|
1469
|
+
return { loaded, local, registered, setup_available, logged_in, identity_version, profile: profile && { ...profile } };
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1313
1472
|
/** Build only non-secret status metadata for the currently selected room. */
|
|
1314
1473
|
function access_snapshot() {
|
|
1315
1474
|
const room = state.room;
|
|
@@ -2900,6 +3059,7 @@ async function initialize() {
|
|
|
2900
3059
|
if (button?.dataset.launchDiscard) discard_launch(button.dataset.launchDiscard);
|
|
2901
3060
|
if (button?.dataset.launchRoom) run_action(() => select_room(button.dataset.launchRoom));
|
|
2902
3061
|
});
|
|
3062
|
+
load_admin_state();
|
|
2903
3063
|
try {
|
|
2904
3064
|
const result = await request_json("/api/rooms");
|
|
2905
3065
|
state.rooms = result.rooms;
|
|
@@ -2911,7 +3071,7 @@ async function initialize() {
|
|
|
2911
3071
|
start_live_updates();
|
|
2912
3072
|
document.addEventListener("visibilitychange", () => {
|
|
2913
3073
|
if (document.hidden) stop_live_updates();
|
|
2914
|
-
else start_live_updates();
|
|
3074
|
+
else { start_live_updates(); load_admin_state(); }
|
|
2915
3075
|
});
|
|
2916
3076
|
window.addEventListener("pagehide", stop_live_updates);
|
|
2917
3077
|
window.addEventListener("pageshow", start_live_updates);
|
|
@@ -2936,7 +3096,7 @@ function view_snapshot() {
|
|
|
2936
3096
|
composer_error: state.composer_error, upload_status: state.upload_status, sending_message: state.sending_message,
|
|
2937
3097
|
mention_only: state.mention_only, reply_to: state.reply_to, turn_reply_to: state.turn_reply_to,
|
|
2938
3098
|
free_notice: state.free_notice, free_error: state.free_error, free_proxy: state.free_proxy,
|
|
2939
|
-
create_parent: state.create_parent, access: access_snapshot(),
|
|
3099
|
+
create_parent: state.create_parent, access: access_snapshot(), admin: admin_snapshot(),
|
|
2940
3100
|
tab: state.tab, snapshot_id: state.snapshot_id, context_dirty: state.context_dirty,
|
|
2941
3101
|
theme: document.documentElement.dataset.theme, fields, experts, launch: structuredClone(state.launch), named_followup: state.named_followup };
|
|
2942
3102
|
}
|
|
@@ -3052,7 +3212,7 @@ async function upload_imported_files(room_id, token, mapping, files) {
|
|
|
3052
3212
|
for (const [old_id, new_id] of Object.entries(mapping)) {
|
|
3053
3213
|
const data = files.get(old_id);
|
|
3054
3214
|
const response = data && await fetch(`/api/rooms/${encodeURIComponent(room_id)}/attachments/${encodeURIComponent(new_id)}/import`,
|
|
3055
|
-
{ method: "POST", headers: { "X-Discussion-Token": token }, body: data });
|
|
3215
|
+
{ method: "POST", headers: { "X-Discussion-Token": token, ...admin_headers() }, body: data });
|
|
3056
3216
|
if (!response?.ok) missing++;
|
|
3057
3217
|
}
|
|
3058
3218
|
return missing;
|
|
@@ -3137,6 +3297,8 @@ window.discuss_view = { snapshot: view_snapshot, write_field: write_view_field,
|
|
|
3137
3297
|
start_drag: start_directory_drag,
|
|
3138
3298
|
attachment_markup, attachment_size, attachment_file_icon, drop_attachments, paste_attachments,
|
|
3139
3299
|
write_expert: write_view_expert, add_instance: add_view_instance, platform_of, execute: execute_view_action, theme: change_view_theme,
|
|
3300
|
+
admin: { register: register_admin, login: login_admin, logout: logout_admin,
|
|
3301
|
+
update_profile: update_admin_profile, avatar_from_file: admin_avatar_from_file, validate: validate_admin_form },
|
|
3140
3302
|
request: request_json, identities: IDENTITIES, display_name, sources: SOURCE_LABELS, phases: PHASE_LABELS,
|
|
3141
3303
|
runtime_label, execution_label, limits_label, participant_model, participant_access, can_retry_execution,
|
|
3142
3304
|
turns: TURN_LABELS, turn_label, turn_guidance, floor_status, progress_round, progress_speaker, brief_meta, max_message_length: MAX_MESSAGE_LENGTH, provenance: message_provenance, format_time };
|