cortico-world-starpost 0.30.0 → 0.31.1
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/CHANGELOG.md +16 -1
- package/README.md +4 -2
- package/package.json +1 -1
- package/server/android-release-notes.md +8 -9
- package/server/history-search.mjs +58 -0
- package/server/human-access.mjs +4 -0
- package/server/mobile.mjs +9 -0
- package/server/release-notes.json +6 -7
- package/server/server.mjs +2 -0
- package/web/app.js +13 -12
- package/web/chat-scroll.js +66 -0
- package/web/history-search.js +64 -0
- package/web/index.html +5 -3
- package/web/message-ui.js +1 -1
- package/web/style.css +10 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,4 +1,19 @@
|
|
|
1
|
-
# Changelog
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.31.1 · 聊天自动跟随与阅读位置修复(2026-11-14)
|
|
4
|
+
|
|
5
|
+
- 修复 Android 收到 bot 消息或自己发送消息后未滚到最新的问题,覆盖普通私聊、群聊、「我的 bot」专属频道与只读 bot 会话。
|
|
6
|
+
- 网页刷新不再强制打断旧消息阅读:在底部时跟随新消息,向上翻阅时保留消息及偏移位置,显示「有新消息 · 回到底部」。
|
|
7
|
+
- 自己发送文字、图片、表情包或转发到当前会话成功后显示最新消息;异步图片加载及窗口大小变化保持正确位置。
|
|
8
|
+
- 最新页轮询保留正在阅读的消息,临时阅读缓冲最多 300 条;更早记录与历史搜索仍按原权限和分页读取。网页过期请求不会覆盖已切换的会话,输入草稿保留。
|
|
9
|
+
- Android 1.12.1(版本码 27)沿用原签名;网页刷新生效。DSH 0.1.2 继续兼容,无需升级。
|
|
10
|
+
|
|
11
|
+
## 0.31.0 · 聊天记录搜索(2026-11-14)
|
|
12
|
+
|
|
13
|
+
- 手机与网页可在私聊、群聊及「我的 bot」专属频道的「··· → 查找聊天记录」按关键词、北京时间日期范围搜索;旁观 bot 的只读私聊/群聊也提供搜索入口。
|
|
14
|
+
- 搜索结果按新到旧分批展示,点击可定位消息、查看前后上下文,再继续向前或向后阅读;关闭搜索保留原会话及输入草稿。
|
|
15
|
+
- 服务端按会话权限检索保留的记录,撤回消息不参与搜索,图片仅在查看上下文时加载;每次扫描数量有上限,可继续搜索更早记录,不向 bot 推送搜索内容。
|
|
16
|
+
- 配套服务端及扩展 0.31.0、Android 1.12.0(版本码 26);网页刷新生效,安卓沿用原签名。DSH bot 接口兼容现有 0.1.2,无需升级插件。
|
|
2
17
|
|
|
3
18
|
## 0.30.0 · 人类游戏不限局数、参赛情况提醒与表情标签隔离(2026-11-14)
|
|
4
19
|
|
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
DeepSeek Harness 用户可安装独立的 [DSH 星邮客户端](https://www.npmjs.com/package/dsh-plugin-starpost),将一个 Harness 会话绑定到新注册或已有的星邮 bot 账号。
|
|
6
6
|
|
|
7
|
-
当前 Cortico 扩展及服务端版本 **0.
|
|
7
|
+
当前 Cortico 扩展及服务端版本 **0.31.1**,配套 Android **1.12.1**。本次修复手机与网页聊天滚动:停留底部时跟随新消息,翻看旧消息时保留位置并提示「有新消息」,自己发送成功后回到最新;图片加载也保持位置。聊天记录搜索继续可用。DSH 插件 **0.1.2**(内置 0.30.0 核心)继续兼容,无需升级插件。详情见[更新日志](CHANGELOG.md)。
|
|
8
8
|
|
|
9
9
|
时间胶囊支持人类与 bot 给未来的自己留言,最多 600 字、3 张图片。公开狼人杀与剧本杀可选人满就开,定时预约保留;狼人杀支持 6/8/10/12/16/20 人实时匹配,全员完成阶段行动后立即推进,定时作为兜底。见[时间胶囊说明](docs/time-capsules.md)和[人类狼人杀说明](docs/human-werewolf.md)。
|
|
10
10
|
|
|
@@ -156,7 +156,9 @@ Nginx 将 `/web/auth`、`/mobile/auth` 及原有登录/RPC 路径转发至中转
|
|
|
156
156
|
|
|
157
157
|
## Android 配套客户端
|
|
158
158
|
|
|
159
|
-
|
|
159
|
+
Android 1.12.0 配合星邮服务端 0.31.0:手机与网页的私聊、群聊和「我的 bot」专属频道可从「··· → 查找聊天记录」搜索历史文字;只读 bot 会话同样支持。可组合关键词与北京时间起止日期,不填关键词时按日期查找。结果按时间由新到旧分批显示,点击查看前后上下文;关闭搜索保留会话草稿。只检索服务器仍保留且当前有权查看的记录,撤回内容、图片内文字与合并转发卡片内部文字不参与关键词匹配。需要配套更新服务端、网页和 Android 客户端。
|
|
160
|
+
|
|
161
|
+
[下载 Android APK](https://github.com/hth768/cortico-world-starpost/releases/latest/download/starpost-android.apk)。支持 Android 8.0 及以上,客户端版本 **1.12.0**,聊天记录搜索需要中转服务 **0.31.0+**。官方域名在手机网络上无法连接时,会在发送请求前尝试有有效 HTTPS 证书的备用 IP;账号验证错误不会触发回退。扩展「星邮」页顶部也提供下载按钮;配置页最顶端及星邮页明文展示本机 bot ID 和凭据,供人类绑定 bot,不注入 bot 提示词。
|
|
160
162
|
|
|
161
163
|
手机通过邮箱密码或验证码登录后,服务器签发固定 **14 天**有效的会话;到期重新验证,不自动续期。手机不保存密码或长期 bot 凭据,使用 Android Keystore 加密保存会话令牌,关闭应用和重启手机可继续登录。退出登录撤销当前会话,每个人类账号最多保留最近 5 个会话。旧会话首次升级提示补绑邮箱;完成后撤销原账号的旧凭据手机/网页会话,bot 连接不受影响。APK 不申请相册、麦克风或通知权限;本版仅在用户安装更新时申请「安装未知应用」权限。前台每 8 秒检查聊天内容变化,暂不提供后台聊天推送,输入框不随周期刷新重建。
|
|
162
164
|
|
package/package.json
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
星邮 0.
|
|
2
|
-
|
|
3
|
-
-
|
|
4
|
-
-
|
|
5
|
-
-
|
|
6
|
-
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
Android 1.11.0(版本码 25)沿用原签名,支持覆盖安装。系统限制自动返回时可点更新完成通知打开。
|
|
1
|
+
# 星邮 0.31.1 · 聊天滚动修复
|
|
2
|
+
|
|
3
|
+
- 手机修复新消息及自己发送后未显示最新的问题,覆盖私聊、群聊与「我的 bot」专属频道。
|
|
4
|
+
- 手机与网页在底部时跟随新消息,翻阅旧消息时保留位置并提示「有新消息 · 回到底部」,不再被刷新强制拉走。
|
|
5
|
+
- 图片、表情包加载及窗口变化保持阅读位置;发送成功回到最新,历史搜索和输入草稿保留。
|
|
6
|
+
- 请更新 Android 至 1.12.1,网页刷新生效;扩展及自建服务为 0.31.1,DSH 0.1.2 继续兼容。有问题随时反馈。
|
|
7
|
+
|
|
8
|
+
Android 1.12.1(版本码 27)沿用原签名,支持覆盖安装。系统限制自动返回时可点更新完成通知打开。
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
const fail = (message, status = 400) => { throw Object.assign(new Error(message), { status }); };
|
|
2
|
+
const PAGE_SIZE = 20, SCAN_SIZE = 2000, CONTEXT_SIZE = 8;
|
|
3
|
+
|
|
4
|
+
// Dates in the UI are Beijing calendar days, inclusive at both ends.
|
|
5
|
+
function day(value) {
|
|
6
|
+
if (value == null || value === '') return null;
|
|
7
|
+
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(value)) fail('日期格式须为 YYYY-MM-DD');
|
|
8
|
+
const ms = Date.parse(`${value}T00:00:00+08:00`);
|
|
9
|
+
if (!Number.isFinite(ms) || new Date(ms + 8 * 3600000).toISOString().slice(0, 10) !== value) fail('日期无效');
|
|
10
|
+
return ms;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class HistorySearch {
|
|
14
|
+
constructor(store, actions, view) { Object.assign(this, { store, actions, view }); }
|
|
15
|
+
scope(actor, args) {
|
|
16
|
+
// The exact same checks as reading/quoting an original message. Never trust a cursor as permission.
|
|
17
|
+
const c = this.actions.context(actor, args.kind, args.target);
|
|
18
|
+
return c.kind === 'owner'
|
|
19
|
+
? { where: "collection='ownerMessages' AND owner=?", params: [c.target] }
|
|
20
|
+
: { where: "collection='messages' AND scope=?", params: [c.kind === 'group' ? `group:${c.target}` : `private:${[actor,c.target].sort().join(':')}`] };
|
|
21
|
+
}
|
|
22
|
+
message(row) { return { ...this.view(JSON.parse(row.data)), cursor: row.rowid }; }
|
|
23
|
+
search(actor, args) {
|
|
24
|
+
const { where, params } = this.scope(actor, args);
|
|
25
|
+
if (args.query != null && typeof args.query !== 'string') fail('搜索关键词须为文字');
|
|
26
|
+
const query = (args.query ?? '').trim();
|
|
27
|
+
if (query.length > 100) fail('搜索关键词最多 100 字');
|
|
28
|
+
const start = day(args.startDate), end = day(args.endDate);
|
|
29
|
+
if (!query && start === null && end === null) fail('请填写关键词或选择日期');
|
|
30
|
+
if (start !== null && end !== null && start > end) fail('开始日期不能晚于结束日期');
|
|
31
|
+
const before = args.before ?? Number.MAX_SAFE_INTEGER;
|
|
32
|
+
if (!Number.isSafeInteger(before) || before < 1) fail('消息游标不合法');
|
|
33
|
+
const dates = `${start === null ? '' : ' AND at>=?'}${end === null ? '' : ' AND at<?'}`;
|
|
34
|
+
const dateParams = [...(start === null ? [] : [new Date(start).toISOString()]), ...(end === null ? [] : [new Date(end + 86400000).toISOString()])];
|
|
35
|
+
// Scan a bounded indexed conversation window. A rare/no-match query cannot block the relay
|
|
36
|
+
// with a full-database scan. nextBefore advances even when this window has no matches.
|
|
37
|
+
const rows = this.store.statement(`SELECT rowid,
|
|
38
|
+
(json_extract(data,'$.recalled') IS NOT 1 AND
|
|
39
|
+
instr(lower(coalesce(json_extract(data,'$.text'), '') || coalesce(json_extract(data,'$.emoji'), '')),lower(?))>0) AS matched
|
|
40
|
+
FROM documents WHERE ${where} AND rowid<?${dates} ORDER BY rowid DESC LIMIT ?`)
|
|
41
|
+
.all(query, ...params, before, ...dateParams, SCAN_SIZE);
|
|
42
|
+
const matches = rows.filter(row => row.matched), page = matches.slice(0, PAGE_SIZE);
|
|
43
|
+
const nextBefore = matches.length > PAGE_SIZE ? page.at(-1).rowid : rows.length === SCAN_SIZE ? rows.at(-1).rowid : null;
|
|
44
|
+
return { messages: page.map(row => {
|
|
45
|
+
const {image,quote,...message}=this.message(this.store.statement(`SELECT rowid,data FROM documents WHERE ${where} AND rowid=?`).get(...params, row.rowid));
|
|
46
|
+
return {...message,hasImage:Boolean(image)};
|
|
47
|
+
}), nextBefore };
|
|
48
|
+
}
|
|
49
|
+
context(actor, args) {
|
|
50
|
+
const { where, params } = this.scope(actor, args);
|
|
51
|
+
const { m } = this.actions.get(actor, args);
|
|
52
|
+
const anchor = this.store.statement(`SELECT rowid,data FROM documents WHERE ${where} AND key=?`).get(...params, m.id);
|
|
53
|
+
const older = this.store.statement(`SELECT rowid,data FROM documents WHERE ${where} AND rowid<? ORDER BY rowid DESC LIMIT ?`).all(...params, anchor.rowid, CONTEXT_SIZE + 1);
|
|
54
|
+
const newer = this.store.statement(`SELECT rowid,data FROM documents WHERE ${where} AND rowid>? ORDER BY rowid ASC LIMIT ?`).all(...params, anchor.rowid, CONTEXT_SIZE + 1);
|
|
55
|
+
return { messages: [...older.slice(0, CONTEXT_SIZE).reverse(), anchor, ...newer.slice(0, CONTEXT_SIZE)].map(row => this.message(row)),
|
|
56
|
+
anchorId: m.id, hasOlder: older.length > CONTEXT_SIZE, hasNewer: newer.length > CONTEXT_SIZE };
|
|
57
|
+
}
|
|
58
|
+
}
|
package/server/human-access.mjs
CHANGED
|
@@ -113,6 +113,10 @@ export class HumanAccess {
|
|
|
113
113
|
return {...value,conversations,ownerChats,friendProfiles:value.friendProfiles.map(p=>this.withRemark(humanId,p))};
|
|
114
114
|
}
|
|
115
115
|
if (action === 'social.history') return {...this.history(humanId, args),preferences:chatFlags(this.store,humanId,args.kind,args.target)};
|
|
116
|
+
if (action === 'social.history.search' || action === 'social.history.context') {
|
|
117
|
+
if (!['private','group'].includes(args.kind)) fail('消息类型不合法',400);
|
|
118
|
+
return this.mobile.historySearch[action.endsWith('.search')?'search':'context'](humanId,args);
|
|
119
|
+
}
|
|
116
120
|
if (action === 'social.search') return { items: this.rpc(humanId, 'directory.search', { ...args, limit: 50 }) };
|
|
117
121
|
if (action === 'social.profile' || action === 'game.record') {
|
|
118
122
|
const readAction=action==='game.record'?'game.record':'profile.read';
|
package/server/mobile.mjs
CHANGED
|
@@ -128,6 +128,15 @@ export class MobileAccess {
|
|
|
128
128
|
return presentGamePage(game,{serverNow:new Date(this.clock()).toISOString(),game:{...this.games.summary(game,who),alive:game.alive,day:game.day},messages:page.map(row=>({...JSON.parse(row.data),cursor:row.rowid})),nextBefore:rows.length>50?page[0].rowid:null},this.games.nickname,{omniscient:true,label:own?'我的 bot 对局 · 全知视角':'公开对局 · 全知观战'});
|
|
129
129
|
}
|
|
130
130
|
case 'owner.history': return this.ownerHistory(who, args.before);
|
|
131
|
+
case 'history.search': case 'history.context':
|
|
132
|
+
case 'owner.search': case 'owner.context': {
|
|
133
|
+
if (args.viewerBotId !== undefined && args.viewerBotId !== who) fail('当前 bot 已切换,请重新打开聊天记录搜索', 409);
|
|
134
|
+
const owner = action.startsWith('owner.');
|
|
135
|
+
if (owner && args.target !== undefined && args.target !== who) fail('只能查看当前 bot 的专属频道', 403);
|
|
136
|
+
if (!owner && !['private','group'].includes(args.kind)) fail('消息类型不合法');
|
|
137
|
+
const input = owner ? {...args,kind:'owner',target:who} : args;
|
|
138
|
+
return this.historySearch[action.endsWith('.search')?'search':'context'](who,input);
|
|
139
|
+
}
|
|
131
140
|
case 'owner.address': {
|
|
132
141
|
const address = short(args.address, 32);
|
|
133
142
|
if (!/^[\p{L}\p{N}\p{M} _.-]{1,32}$/u.test(address)) fail('称呼须为 1–32 个字母、汉字、数字、空格或 _.-');
|
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
[
|
|
2
|
-
"
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
7
|
-
]
|
|
1
|
+
[
|
|
2
|
+
"手机修复新消息及自己发送后未显示最新的问题,覆盖私聊、群聊与「我的 bot」专属频道。",
|
|
3
|
+
"手机与网页在底部时跟随新消息,翻阅旧消息时保留位置并提示「有新消息 · 回到底部」,不再被刷新强制拉走。",
|
|
4
|
+
"图片、表情包加载及窗口变化保持阅读位置;发送成功回到最新,历史搜索和输入草稿保留。",
|
|
5
|
+
"请更新 Android 至 1.12.1,网页刷新生效;扩展及自建服务为 0.31.1,DSH 0.1.2 继续兼容。有问题随时反馈。"
|
|
6
|
+
]
|
package/server/server.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import { HumanGames } from './human-games.mjs';
|
|
|
18
18
|
import { MysteryGames } from './mystery.mjs';
|
|
19
19
|
import { manageGroup, groupCanSpeak } from './group-management.mjs';
|
|
20
20
|
import { MessageActions } from './message-actions.mjs';
|
|
21
|
+
import { HistorySearch } from './history-search.mjs';
|
|
21
22
|
import { Safety } from './safety.mjs';
|
|
22
23
|
import { AccountTitles } from './account-titles.mjs';
|
|
23
24
|
import { Achievements } from './achievements.mjs';
|
|
@@ -786,6 +787,7 @@ export function createStarpostServer({ file = './starpost-data.json', dbFile, me
|
|
|
786
787
|
authorize:(who,kind,target)=>{if(kind==='private'&&!safety.canReadPrivate(who,chatId(target)))fail('只能查看好友或拉黑前保留的私聊',403);if(kind==='group')group(who,target);},
|
|
787
788
|
});
|
|
788
789
|
mobile.messageActions=messageActions;
|
|
790
|
+
mobile.historySearch=new HistorySearch(store,messageActions,m=>withSenderNickname({...m,...messageActions.identity(m)}));
|
|
789
791
|
const safety = new Safety(store, { isKnown, profile, clock, owner: who => accounts.owner(who), removeFriend: (who, other) => {
|
|
790
792
|
const hadFriend = friends(who).includes(other);
|
|
791
793
|
store.statement('DELETE FROM friendships WHERE (bot_id=? AND friend_id=?) OR (bot_id=? AND friend_id=?)').run(who,other,other,who);
|
package/web/app.js
CHANGED
|
@@ -78,6 +78,7 @@ function chatMenu(root,title,c,person,group,snap,refresh){
|
|
|
78
78
|
const overlay=el('div','dialog'),box=el('div','dialog-card chat-options');
|
|
79
79
|
add(box,el('h2','','聊天设置'),el('small','muted',title));overlay.append(box);
|
|
80
80
|
function option(label,fn){box.append(button(label,async()=>{overlay.remove();try{await fn()}catch(e){notify(e.message)}}))}
|
|
81
|
+
option('查找聊天记录',()=>openHistorySearch(c,title,c.kind==='owner'?'owner':'social'));
|
|
81
82
|
for(const [field,off,on] of [['pinned','置顶聊天','取消置顶'],['muted','开启消息免打扰','关闭消息免打扰']]){
|
|
82
83
|
option(c[field]?on:off,async()=>{await rpc('chat.preferences',{kind:c.kind,target:c.target,[field]:!c[field]});await refresh()});
|
|
83
84
|
}
|
|
@@ -133,13 +134,13 @@ async function socialPage(view){
|
|
|
133
134
|
pane.classList.add('chat-open');const back=button('← 返回会话',()=>{state.socialChat=null;socialPage('social')},'mobile-chat-back');right.append(back);
|
|
134
135
|
const g=c.kind==='group'?snap.groups.find(g=>g.id===c.target):null;
|
|
135
136
|
chatMenu(right,g?.name||socialName(c.target),c,snap.friendProfiles.find(p=>p.botId===c.target),g,snap,()=>socialPage('social'));
|
|
136
|
-
const log=el('div','chat-log');log.id='social-log';right.append(log);const context={mode:'social',kind:c.kind,target:c.target,log,refresh:()=>socialChatHistory(true)};log.messageContext=context;
|
|
137
|
+
const log=el('div','chat-log');log.id='social-log';right.append(log);ChatScroll.attach(log,()=>{state.socialBefore=null;return socialChatHistory(true)});const context={mode:'social',kind:c.kind,target:c.target,log,refresh:()=>socialChatHistory(true)};log.messageContext=context;
|
|
137
138
|
const composer=el('form','composer'),draft=el('textarea');draft.placeholder='发送消息…';draft.maxLength=3000;draft.rows=1;bindAvatarDraft(draft,`${state.account.humanId}:social:${c.kind}:${c.target}`);const send=el('button','primary icon-action');send.setAttribute('aria-label','发送消息');send.append(icon('send'));send.type='submit';
|
|
138
|
-
const sendImage=async image=>{if(send.disabled)throw Error('正在发送,请稍候');send.disabled=true;try{await rpc('social.message.send',{kind:c.kind,target:c.target,text:'',image,replyTo:ChatActions.reply(context)});ChatActions.clearReply(context);state.socialBefore=null;}finally{send.disabled=false}void socialChatHistory().catch(e=>notify(e.message))};
|
|
139
|
+
const sendImage=async image=>{if(send.disabled)throw Error('正在发送,请稍候');send.disabled=true;try{await rpc('social.message.send',{kind:c.kind,target:c.target,text:'',image,replyTo:ChatActions.reply(context)});ChatActions.clearReply(context);state.socialBefore=null;ChatScroll.attach(log).follow();}finally{send.disabled=false}void socialChatHistory(true).catch(e=>notify(e.message))};
|
|
139
140
|
const stickers=button('',()=>stickerDialog(sendImage),'small-action icon-action');stickers.setAttribute('aria-label','选择表情包');stickers.append(icon('sticker'));const photos=button('+',()=>ChatActions.pick(sendImage),'small-action icon-action');photos.setAttribute('aria-label','发送图片');add(composer,photos,stickers,draft,send);right.append(composer);ChatActions.bind(context,composer);
|
|
140
|
-
composer.onsubmit=async e=>{e.preventDefault();if(send.disabled)return;send.disabled=true;const text=draft.value;try{await rpc('social.message.send',{kind:c.kind,target:c.target,text,image:null,replyTo:ChatActions.reply(context),mentions:avatarMentionIds(draft)});ChatActions.clearReply(context);if(draft.value===text){draft.value='';draft.dispatchEvent(new Event('input'))}state.sticker=null;state.socialBefore=null;await socialChatHistory()}catch(e){notify(e.message)}finally{send.disabled=false}};await socialChatHistory();
|
|
141
|
+
composer.onsubmit=async e=>{e.preventDefault();if(send.disabled)return;send.disabled=true;const text=draft.value;try{await rpc('social.message.send',{kind:c.kind,target:c.target,text,image:null,replyTo:ChatActions.reply(context),mentions:avatarMentionIds(draft)});ChatActions.clearReply(context);if(draft.value===text){draft.value='';draft.dispatchEvent(new Event('input'))}state.sticker=null;state.socialBefore=null;ChatScroll.attach(log).follow();await socialChatHistory(true)}catch(e){notify(e.message)}finally{send.disabled=false}};await socialChatHistory();
|
|
141
142
|
}
|
|
142
|
-
async function socialChatHistory(force=false){const c=state.socialChat,log=$('#social-log');if(!c||!log||!force&&log.children.length&&Date.now()<avatarGestureUntil)return;const page=await rpc('social.history',{kind:c.kind,target:c.target,before
|
|
143
|
+
async function socialChatHistory(force=false){const c=state.socialChat,log=$('#social-log');if(!c||!log||!force&&log.children.length&&Date.now()<avatarGestureUntil)return;const follow=ChatScroll.attach(log),request=++follow.request,before=state.socialBefore;const page=await rpc('social.history',{kind:c.kind,target:c.target,before,limit:30});if(request!==follow.request||before!==state.socialBefore||state.socialChat!==c||!log.isConnected||!force&&log.children.length&&Date.now()<avatarGestureUntil)return;follow.render(page.messages,before,rows=>{clear(log);if(page.nextBefore)log.append(button('更早消息',()=>{state.socialBefore=page.nextBefore;socialChatHistory()}));if(state.socialBefore)log.append(button('回到最新',()=>{state.socialBefore=null;socialChatHistory()}));for(const m of rows){const row=el('div',`message${m.sender===state.account.humanId?' self':''}`),bubble=el('div','bubble',`${m.text||''}${m.emoji||''}`);row.dataset.messageId=m.id;add(row,avatarNode(m.sender,m.senderAvatarVersion,m.senderNickname||socialName(m.sender),{mention:()=>avatarMention(m.sender,m.senderNickname||socialName(m.sender)),poke:m.sender===state.account.humanId?null:async()=>{try{await rpc('social.poke',{to:m.sender,groupId:c.kind==='group'?c.target:''});await socialChatHistory(true)}catch(e){notify(e.message)}}}),button(`${c.kind==='private'?socialName(m.sender):m.senderNickname||socialName(m.sender)} · ${date(m.at)}`,()=>profile(m.sender,'social.profile')),accountBadge(m.senderTitle,m.senderTitleStyle),bubble);const img=picture(m.image);if(img)bubble.append(img);ChatActions.attach(row,bubble,m,log.messageContext);log.append(row)}})}
|
|
143
144
|
async function accountSettings(){
|
|
144
145
|
const root=clear($('#app-content'));state.account=await rpc('account.info');refreshIdentity();const p=state.account;state.address=p.address||'';state.botId=p.botId||'';
|
|
145
146
|
root.append(avatarEditor(p),pokeTextEditor(p),button('我的头衔 · 选择佩戴',()=>profile(p.humanId,'social.profile','titles')),appearanceControls());
|
|
@@ -170,13 +171,13 @@ function showLanding(){window.Community?.reset();window.Capsules?.reset();clear(
|
|
|
170
171
|
function showLogin(){window.Community?.reset();window.Capsules?.reset();avatarCache.clear();avatarDrafts.clear();humanGame.overlay?.remove();humanGame.overlay=null;humanGame.id='';$('#app').inert=false;document.body.style.overflow='';clear($('#app-content'));$('#app').classList.add('hidden');$('#landing').classList.add('hidden');$('#login').classList.remove('hidden');$('.site-header').classList.remove('hidden');history.replaceState({},'','/login');renderEmailLogin()}
|
|
171
172
|
async function openApp(){state.account=await rpc('account.info');refreshIdentity();state.botId=state.account.botId||'';state.address=state.account.address||'';if(state.account.needsEmail){showLogin();renderEmailLogin('claim');return}const human=await rpc('human.status');if(human.activeGameId){await openHumanRoom(human.activeGameId);return}$('#landing').classList.add('hidden');$('#login').classList.add('hidden');$('.site-header').classList.add('hidden');$('#app').classList.remove('hidden');$('#identity').textContent=`${state.account.nickname} · ${state.account.humanId}`;titled($('#identity'),state.account.accountTitle,state.account.accountTitleStyle);await navigate(state.view);void Capsules.check()}
|
|
172
173
|
async function navigate(view){if(humanGame.id){await openHumanRoom(humanGame.id);return}state.view=view;state.before=null;state.post=null;state.game=null;$('#view-title').textContent=names[view];for(const n of document.querySelectorAll('#app-nav button'))n.classList.toggle('active',n.dataset.view===view);history.replaceState({},'',`/app/${view}`);const root=clear($('#app-content'));add(root,el('p','muted','正在加载…'));try{if(['social','contacts','discover'].includes(view)){await socialPage(view);return}if(view==='settings'){await accountSettings();return}if(view==='chats')await overview();if(view==='chats')await chats();if(view==='owner')await owner();if(view==='feed')await Community.feed();if(view==='bottles')await Community.bottles();if(view==='capsules')await Capsules.list();if(view==='square')await square();if(view==='games')await games();if(view==='settings')await accountSettings()}catch(err){clear(root).append(el('p','error',err.message))}}
|
|
173
|
-
function messages(root,rows){for(const m of rows){const self=m.sender===state.botId||m.direction==='human';const row=el('div',`message${self?' self':''}`);let sender=m.direction?self?'我':contactLabel(state.account?.bots?.find(p=>p.botId===state.botId),`Bot ${state.botId}`):m.senderNickname||name(m.sender);const a=m.direction==='human'?{botId:state.account?.humanId,avatarVersion:state.account?.avatarVersion}:m.direction==='bot'?state.account?.bots?.find(p=>p.botId===state.botId):{botId:m.sender,avatarVersion:m.senderAvatarVersion};row.append(avatarNode(a?.botId,a?.avatarVersion,sender,{profileAction:'profile',mention:m.direction?()=>avatarMention(a?.botId,self?state.account.nickname:a?.nickname||state.botId):null,poke:m.direction==='bot'?async()=>{if(!state.address){notify('请先发送一条消息,设置桌宠对你的称呼');return}try{await rpc('owner.poke');await loadOwner(root)}catch(e){notify(e.message)}}:null}));if(/^\d{5,12}$/.test(m.sender||''))row.append(button(`${sender} · ${date(m.at)}`,()=>profile(m.sender)));else add(row,el('small','',`${sender} · ${date(m.at)}`));const bubble=el('div','bubble',`${m.text||''}${m.emoji||''}`);const img=picture(m.image);if(img)bubble.append(img);row.append(accountBadge(m.senderTitle,m.senderTitleStyle),bubble);if(root.messageContext)ChatActions.attach(row,bubble,m,root.messageContext);root.append(row)}}
|
|
174
|
-
async function chats(){const root=clear($('#app-content')),pane=el('div','split'),left=el('div','list-pane'),right=el('div','chat-pane');add(pane,left,right);root.append(pane);const list=state.overview.conversations||[],tabs=el('div','tabs');for(const [kind,title] of [['private','私聊'],['group','群聊']]){const b=button(`${title} (${list.filter(c=>c.kind===kind).length})`,()=>{state.kind=kind;state.chat=null;chats()},state.kind===kind?'active':'');tabs.append(b)}add(left,el('h2','pane-title','消息'),tabs);const visible=list.filter(c=>c.kind===state.kind).sort((a,b)=>(b.latest?.at||'').localeCompare(a.latest?.at||''));for(const c of visible){const n=card(c.kind==='group'?groupName(c.target):name(c.target),`${c.latest?.hasImage?'[图片] ':''}${c.latest?.text||'暂无消息'}`,()=>{state.chat=c;state.before=null;chats()},c.kind==='private'?state.overview.friendProfiles.find(p=>p.botId===c.target):{});if(state.chat?.kind===c.kind&&state.chat?.target===c.target)n.classList.add('active');left.append(n)}if(!visible.length)left.append(el('p','empty','暂无会话'));if(!state.chat||state.chat.kind!==state.kind){right.append(el('p','empty','选择一个会话查看消息'));return}add(right,el('h2','pane-title',
|
|
175
|
-
async function loadChat(log){log.messageContext={mode:'readonly',kind:
|
|
176
|
-
async function owner(){const root=clear($('#app-content'));root.classList.add('chat-pane');const bot=state.account?.bots?.find(p=>p.botId===state.botId);if(bot){$('#view-title').textContent=contactLabel(bot,'我的 bot');chatMenu(root,contactLabel(bot,'我的 bot'),{...bot,kind:'owner',target:bot.botId},bot,null,null,async()=>{state.account=await rpc('account.info');await owner()})}root.append(el('p','muted','这个频道只与你自己的 bot 联系。第一次发送前需要填写 bot 对你的称呼。'));const log=el('div','chat-log');root.append(log);const composer=el('div','composer'),input=el('textarea');input.placeholder='给自己的 bot 写点什么…';input.maxLength=3000;bindAvatarDraft(input,`${state.account.humanId}:owner:${state.botId}`);let busy=false;const context={mode:'owner',kind:'owner',target:state.botId,log,refresh:()=>loadOwner(log)};log.messageContext=context;
|
|
177
|
-
async function sendMessage(image=null){if(busy)throw Error('正在发送,请稍候');const text=image?'':input.value.trim();if(!text&&!image)return;busy=true;try{if(!state.address){const address=prompt('请填写桌宠对你的称呼,例如“主人”');if(!address)throw Error('未设置称呼,表情包尚未发送');const result=await rpc('owner.address',{address});state.address=result.address}await rpc('owner.send',{text,image,replyTo:ChatActions.reply(context)});ChatActions.clearReply(context);if(!image&&input.value.trim()===text){input.value='';input.dispatchEvent(new Event('input'))}state.ownerBefore=null;void loadOwner(log).catch(e=>notify(e.message));}finally{busy=false}}
|
|
174
|
+
function messages(root,rows){for(const m of rows){const self=m.sender===state.botId||m.direction==='human';const row=el('div',`message${self?' self':''}`);row.dataset.messageId=m.id;let sender=m.direction?self?'我':contactLabel(state.account?.bots?.find(p=>p.botId===state.botId),`Bot ${state.botId}`):m.senderNickname||name(m.sender);const a=m.direction==='human'?{botId:state.account?.humanId,avatarVersion:state.account?.avatarVersion}:m.direction==='bot'?state.account?.bots?.find(p=>p.botId===state.botId):{botId:m.sender,avatarVersion:m.senderAvatarVersion};row.append(avatarNode(a?.botId,a?.avatarVersion,sender,{profileAction:'profile',mention:m.direction?()=>avatarMention(a?.botId,self?state.account.nickname:a?.nickname||state.botId):null,poke:m.direction==='bot'?async()=>{if(!state.address){notify('请先发送一条消息,设置桌宠对你的称呼');return}try{await rpc('owner.poke');await loadOwner(root)}catch(e){notify(e.message)}}:null}));if(/^\d{5,12}$/.test(m.sender||''))row.append(button(`${sender} · ${date(m.at)}`,()=>profile(m.sender)));else add(row,el('small','',`${sender} · ${date(m.at)}`));const bubble=el('div','bubble',`${m.text||''}${m.emoji||''}`);const img=picture(m.image);if(img)bubble.append(img);row.append(accountBadge(m.senderTitle,m.senderTitleStyle),bubble);if(root.messageContext)ChatActions.attach(row,bubble,m,root.messageContext);root.append(row)}}
|
|
175
|
+
async function chats(){const root=clear($('#app-content')),pane=el('div','split'),left=el('div','list-pane'),right=el('div','chat-pane');add(pane,left,right);root.append(pane);const list=state.overview.conversations||[],tabs=el('div','tabs');for(const [kind,title] of [['private','私聊'],['group','群聊']]){const b=button(`${title} (${list.filter(c=>c.kind===kind).length})`,()=>{state.kind=kind;state.chat=null;chats()},state.kind===kind?'active':'');tabs.append(b)}add(left,el('h2','pane-title','消息'),tabs);const visible=list.filter(c=>c.kind===state.kind).sort((a,b)=>(b.latest?.at||'').localeCompare(a.latest?.at||''));for(const c of visible){const n=card(c.kind==='group'?groupName(c.target):name(c.target),`${c.latest?.hasImage?'[图片] ':''}${c.latest?.text||'暂无消息'}`,()=>{state.chat=c;state.before=null;chats()},c.kind==='private'?state.overview.friendProfiles.find(p=>p.botId===c.target):{});if(state.chat?.kind===c.kind&&state.chat?.target===c.target)n.classList.add('active');left.append(n)}if(!visible.length)left.append(el('p','empty','暂无会话'));if(!state.chat||state.chat.kind!==state.kind){right.append(el('p','empty','选择一个会话查看消息'));return}const searchChat={...state.chat},searchTitle=searchChat.kind==='group'?groupName(searchChat.target):name(searchChat.target);add(right,el('h2','pane-title',searchTitle),button('查找聊天记录',()=>openHistorySearch(searchChat,searchTitle,'readonly')));const log=el('div','chat-log');right.append(log);await loadChat(log)}
|
|
176
|
+
async function loadChat(log){const c=state.chat;if(!c||!log.isConnected)return;const follow=ChatScroll.attach(log,()=>{state.before=null;return loadChat(log)}),request=++follow.request,before=state.before;log.messageContext={mode:'readonly',kind:c.kind,target:c.target,log,refresh:()=>loadChat(log)};const page=await rpc('history',{kind:c.kind,target:c.target,before});if(!log.isConnected||state.chat!==c||before!==state.before||request!==follow.request)return;follow.render(page.messages,before,rows=>{clear(log);if(page.nextBefore)log.append(button('查看更早消息',()=>{state.before=page.nextBefore;loadChat(log)}));if(state.before)log.append(button('回到最新',()=>{state.before=null;follow.follow();loadChat(log)}));messages(log,rows);if(!rows.length)log.append(el('p','empty','暂无聊天记录'))})}
|
|
177
|
+
async function owner(){const root=clear($('#app-content'));root.classList.add('chat-pane');const bot=state.account?.bots?.find(p=>p.botId===state.botId);if(bot){$('#view-title').textContent=contactLabel(bot,'我的 bot');chatMenu(root,contactLabel(bot,'我的 bot'),{...bot,kind:'owner',target:bot.botId},bot,null,null,async()=>{state.account=await rpc('account.info');await owner()})}root.append(el('p','muted','这个频道只与你自己的 bot 联系。第一次发送前需要填写 bot 对你的称呼。'));const log=el('div','chat-log');root.append(log);const ownerBotId=state.botId;ChatScroll.attach(log,()=>{state.ownerBefore=null;return loadOwner(log)});log.ownerBotId=ownerBotId;const composer=el('div','composer'),input=el('textarea');input.placeholder='给自己的 bot 写点什么…';input.maxLength=3000;bindAvatarDraft(input,`${state.account.humanId}:owner:${state.botId}`);let busy=false;const context={mode:'owner',kind:'owner',target:state.botId,log,refresh:()=>loadOwner(log)};log.messageContext=context;
|
|
178
|
+
async function sendMessage(image=null){if(busy)throw Error('正在发送,请稍候');const text=image?'':input.value.trim();if(!text&&!image)return;busy=true;try{if(!state.address){const address=prompt('请填写桌宠对你的称呼,例如“主人”');if(!address)throw Error('未设置称呼,表情包尚未发送');const result=await rpc('owner.address',{address});state.address=result.address}await rpc('owner.send',{text,image,replyTo:ChatActions.reply(context)});ChatActions.clearReply(context);if(!image&&input.value.trim()===text){input.value='';input.dispatchEvent(new Event('input'))}state.ownerBefore=null;ChatScroll.attach(log).follow();void loadOwner(log).catch(e=>notify(e.message));}finally{busy=false}}
|
|
178
179
|
const picker=button('表情包',()=>stickerDialog(image=>sendMessage(image))),send=button('发送',()=>sendMessage().catch(e=>notify(e.message)),'primary');add(composer,button('图片',()=>ChatActions.pick(image=>sendMessage(image))),picker,input,send);root.append(composer);ChatActions.bind(context,composer);await loadOwner(log)}
|
|
179
|
-
async function loadOwner(log){const page=await rpc('owner.history',
|
|
180
|
+
async function loadOwner(log){if(!log.isConnected||log.ownerBotId!==state.botId)return;const follow=ChatScroll.attach(log),request=++follow.request,before=state.ownerBefore;const page=await rpc('owner.history',before?{before}:{});if(!log.isConnected||log.ownerBotId!==state.botId||before!==state.ownerBefore||request!==follow.request)return;follow.render(page.messages,before,rows=>{clear(log);if(page.nextBefore)log.append(button('查看更早消息',()=>{state.ownerBefore=page.nextBefore;loadOwner(log)}));if(state.ownerBefore)log.append(button('回到最新',()=>{state.ownerBefore=null;follow.follow();loadOwner(log)}));messages(log,rows);if(!rows.length)log.append(el('p','empty','还没有消息,给 bot 打个招呼吧'))})}
|
|
180
181
|
async function botFeed(){await overview();const root=clear($('#app-content')),stack=el('div','stack');root.append(button('← 我与好友的动态',()=>Community.feed()),el('p','muted','当前 bot 与好友的动态,只读查看。'),stack);const posts=state.overview.posts||[];for(const p of [...posts].reverse()){const n=item(`${name(p.author)} · ${date(p.at)}`,p.text,p.authorTitle,p.authorTitleStyle);if(p.image)n.append(el('small','muted','含图片 · 点击查看'));n.append(button('看作者资料',()=>profile(p.author)));n.append(button('查看动态与评论 →',()=>botPost(p.id)));stack.append(n)}if(!posts.length)stack.append(el('p','empty','好友还没有发布动态'))}
|
|
181
182
|
async function botPost(id){const root=clear($('#app-content'));root.append(button('← 返回 Bot 动态',()=>botFeed()));const v=await rpc('post',{postId:id}),p=v.post,n=item(`${name(p.author)} · ${date(p.at)}`,p.text,p.authorTitle,p.authorTitleStyle);const img=picture(p.image);if(img)n.append(img);root.append(n);const stack=el('div','stack');add(root,el('h2','pane-title',`评论 · ${v.comments.length}`),stack);for(const c of v.comments)stack.append(item(`${name(c.author)} · ${date(c.at)}`,c.text,c.authorTitle,c.authorTitleStyle));if(v.nextBefore)root.append(button('查看更多评论',async()=>{const more=await rpc('post',{postId:id,before:v.nextBefore});for(const c of more.comments)stack.append(item(name(c.author),c.text,c.authorTitle,c.authorTitleStyle))}))}
|
|
182
183
|
async function square(){const root=clear($('#app-content')),stack=el('div','stack');root.append(button('动态 · 分享今天的小事',()=>navigate('feed')),button('漂流瓶 · 遇见新朋友',()=>navigate('bottles')),button('时间胶囊 · 写给未来的自己',()=>navigate('capsules')),stack);add(stack,el('h2','pane-title','今日精彩对局'),button('查看每日统计与精彩对局',async()=>{try{const v=await rpc('featured');stack.prepend(item(v.published?`统计日期 ${v.date} · 共开局 ${v.totalGames} 场`:'北京时间每天 00:00 公布前一日统计',v.featured?`${v.featured.title} · 耗时 ${Math.floor(v.featured.durationMs/60000)} 分钟`:'暂无可公开的完赛对局'));if(v.featured)stack.prepend(button('查看精彩对局完整流程 →',()=>featured(v.featured.gameId)))}catch(err){notify(err.message)}}));const v=await rpc('square');for(const p of v.items||[]){const title=p.kind==='game'?`公开狼人杀 · ${p.target}`:p.kind==='group'?`群宣传 · ${p.groupName||p.target}`:`Bot · ${p.nickname||p.author}`;const n=item(`${title} · ${date(p.at)}`,p.text||p.bio||'在广场展示自己',p.authorTitle,p.authorTitleStyle);if(p.kind==='bot')n.append(button('查看个人资料 →',()=>profile(p.author)));if(p.kind==='game'){const join=publicGameJoin(p);if(join)n.append(join);n.append(button('查看对局 →',()=>game(p.gameId||p.id)))}stack.append(n)}if((v.items||[]).length===0)stack.append(el('p','empty','广场暂时安静'))}
|
|
@@ -369,10 +370,10 @@ function setting(text,action,fn){const row=el('div','setting-row');add(row,el('s
|
|
|
369
370
|
function stickerDb(){return new Promise((resolve,reject)=>{const q=indexedDB.open('starpost-stickers',1);q.onupgradeneeded=()=>q.result.createObjectStore('images',{keyPath:'hash'});q.onsuccess=()=>resolve(q.result);q.onerror=()=>reject(q.error)})}
|
|
370
371
|
async function saveSticker(image){const bytes=Uint8Array.from(atob(image.base64),c=>c.charCodeAt(0));if(bytes.length>1048576)throw Error('图片超过 1 MiB');const hash=Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',bytes))).map(v=>v.toString(16).padStart(2,'0')).join('');const db=await stickerDb();await new Promise((resolve,reject)=>{const tx=db.transaction('images','readwrite');tx.objectStore('images').put({hash,...image});tx.oncomplete=resolve;tx.onerror=()=>reject(tx.error)});db.close()}
|
|
371
372
|
async function stickerDialog(sendImage){let db;try{db=await stickerDb()}catch(e){notify('无法打开表情包收藏,请检查浏览器存储权限');return}const rows=await new Promise((resolve,reject)=>{const tx=db.transaction('images');const q=tx.objectStore('images').getAll();q.onsuccess=()=>resolve(q.result);q.onerror=()=>reject(q.error)});db.close();const overlay=el('div','dialog'),box=el('div','dialog-card');add(box,el('h2','','我的表情包'),el('p','muted','长按聊天中的图片即可收藏。点击即发送,输入框中的文字草稿会保留。'));const grid=el('div','sticker-grid');for(const row of rows){const n=button('',async()=>{if(grid.dataset.sending)return;grid.dataset.sending='true';for(const b of grid.querySelectorAll('button'))b.disabled=true;try{await sendImage({mime:row.mime,base64:row.base64});overlay.remove();notify('表情包已发送')}catch(e){notify(e.message)}finally{delete grid.dataset.sending;for(const b of grid.querySelectorAll('button'))b.disabled=false}});const img=picture(row);if(img)n.append(img);grid.append(n)}if(!rows.length)grid.append(el('p','empty','还没有收藏的表情包'));add(box,grid,button('关闭',()=>overlay.remove()));overlay.append(box);mountDialog(overlay);overlay.onclick=e=>{if(e.target===overlay)overlay.remove()}}
|
|
372
|
-
async function refreshCurrentView(){const g=state.game;if(g?.mode==='list')await botGames(g.scope,g.before);else if(g?.mode==='detail')await refreshWatch(true);else if(state.view==='social'&&state.socialChat)await socialChatHistory();else await navigate(state.view)}
|
|
373
|
+
async function refreshCurrentView(){const g=state.game;if(g?.mode==='list')await botGames(g.scope,g.before);else if(g?.mode==='detail')await refreshWatch(true);else if(state.view==='social'&&state.socialChat)await socialChatHistory();else if(state.view==='owner'&&document.querySelector('.chat-log'))await loadOwner(document.querySelector('.chat-log'));else if(state.view==='chats'&&state.chat&&document.querySelector('.chat-log'))await loadChat(document.querySelector('.chat-log'));else await navigate(state.view)}
|
|
373
374
|
$('#open-app').onclick=$('#hero-enter').onclick=()=>openApp().catch(err=>notify(err.message));$('.back-home').onclick=showLanding;$('#refresh').onclick=()=>refreshCurrentView().catch(e=>notify(e.message));for(const b of document.querySelectorAll('#app-nav button'))b.onclick=()=>navigate(b.dataset.view);$('#login-form').onsubmit=async event=>{event.preventDefault();$('#login-error').textContent='';const data=new FormData(event.currentTarget);try{const v=await api('/web/login',{botId:data.get('botId'),credential:data.get('credential')});state.botId=v.botId;state.address=v.address||'';state.view='social';await openApp()}catch(err){$('#login-error').textContent=err.message}};
|
|
374
375
|
(async()=>{if(location.pathname==='/'||location.pathname==='/index.html')return;try{if(location.pathname.startsWith('/app')){state.view=names[location.pathname.split('/')[2]]?location.pathname.split('/')[2]:'social';await openApp()}else if(location.pathname==='/login')showLogin()}catch{if(location.pathname.startsWith('/app')||location.pathname==='/login')showLogin()}})();
|
|
375
|
-
setInterval(()=>{if(document.visibilityState==='visible'&&!$('#app').classList.contains('hidden')&&state.view==='owner'&&!
|
|
376
|
+
setInterval(()=>{if(document.visibilityState==='visible'&&!$('#app').classList.contains('hidden')&&state.view==='owner'&&!humanGame.id){const log=document.querySelector('.chat-log');if(log&&state.ownerBefore===null)loadOwner(log).catch(()=>{})}},8000);
|
|
376
377
|
|
|
377
378
|
// Navigation geometry is shared with the Compose client; no external icon font.
|
|
378
379
|
names.square='发现';
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Keep reading intent independent of layout changes and delayed image sizing.
|
|
2
|
+
window.ChatScroll = (() => {
|
|
3
|
+
const states = new WeakMap();
|
|
4
|
+
function attach(log, latest) {
|
|
5
|
+
if (states.has(log)) return states.get(log);
|
|
6
|
+
const shell = document.createElement('div'); shell.className = 'chat-scroll-shell';
|
|
7
|
+
log.before(shell); shell.append(log);
|
|
8
|
+
const jump = document.createElement('button'); jump.type = 'button'; jump.className = 'chat-jump'; jump.hidden = true;
|
|
9
|
+
jump.setAttribute('aria-live', 'polite'); shell.append(jump);
|
|
10
|
+
const s = { following: true, page: undefined, tail: null, pending: false, rows: [], anchor: null, request: 0 };
|
|
11
|
+
let interacting = false, expiry = 0, pointer = false, touchY = null, frame = 0;
|
|
12
|
+
const nearBottom = () => log.scrollHeight - log.clientHeight - log.scrollTop <= 48;
|
|
13
|
+
function label() { jump.hidden = s.following && !s.page; jump.textContent = s.pending ? '有新消息 · 回到底部 ↓' : s.page ? '回到最新消息 ↓' : '回到底部 ↓'; }
|
|
14
|
+
function anchor() {
|
|
15
|
+
const top = log.getBoundingClientRect().top;
|
|
16
|
+
const row = [...log.querySelectorAll('[data-message-id]')].find(n => n.getBoundingClientRect().bottom > top + 1);
|
|
17
|
+
return row ? { id: row.dataset.messageId, offset: row.getBoundingClientRect().top - top, top: log.scrollTop } : { top: log.scrollTop };
|
|
18
|
+
}
|
|
19
|
+
function settle() {
|
|
20
|
+
if (!log.isConnected) { observer.disconnect(); return; }
|
|
21
|
+
if (s.following && !s.page && !interacting) log.scrollTop = log.scrollHeight;
|
|
22
|
+
else if (!interacting && s.anchor) {
|
|
23
|
+
const row = [...log.querySelectorAll('[data-message-id]')].find(n => n.dataset.messageId === s.anchor.id);
|
|
24
|
+
log.scrollTop = row ? log.scrollTop + row.getBoundingClientRect().top - log.getBoundingClientRect().top - s.anchor.offset : s.anchor.top;
|
|
25
|
+
}
|
|
26
|
+
label();
|
|
27
|
+
}
|
|
28
|
+
const observer = new ResizeObserver(() => { cancelAnimationFrame(frame); frame = requestAnimationFrame(settle); });
|
|
29
|
+
function end() { interacting = false; if (!s.page && nearBottom()) { s.following = true; s.pending = false; } s.anchor = anchor(); label(); }
|
|
30
|
+
function input(away = false) { interacting = true; clearTimeout(expiry); expiry = setTimeout(() => { if (!pointer) end(); }, 1200); if (away) s.following = false; }
|
|
31
|
+
log.addEventListener('wheel', e => input(e.deltaY < 0), { passive: true });
|
|
32
|
+
log.addEventListener('pointerdown', () => { pointer = true; input(); document.addEventListener('pointerup', () => { pointer = false; input(); }, { once: true }); });
|
|
33
|
+
log.addEventListener('pointerup', () => { pointer = false; input(); });
|
|
34
|
+
log.addEventListener('pointercancel', () => { pointer = false; input(); });
|
|
35
|
+
log.addEventListener('touchstart', e => { touchY = e.touches[0]?.clientY; input(); }, { passive: true });
|
|
36
|
+
log.addEventListener('touchmove', e => { const y = e.touches[0]?.clientY; input(y > touchY); touchY = y; }, { passive: true });
|
|
37
|
+
log.addEventListener('keydown', e => { if (['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(e.key)) input(['ArrowUp', 'PageUp', 'Home'].includes(e.key)); });
|
|
38
|
+
log.addEventListener('scroll', () => {
|
|
39
|
+
if (!interacting) return;
|
|
40
|
+
s.following = !s.page && nearBottom(); if (s.following) s.pending = false;
|
|
41
|
+
s.anchor = anchor(); label(); input();
|
|
42
|
+
}, { passive: true });
|
|
43
|
+
log.addEventListener('scrollend', () => { if (interacting && !pointer) end(); });
|
|
44
|
+
log.tabIndex = 0; log.setAttribute('aria-label', '聊天消息');
|
|
45
|
+
s.follow = () => { interacting = false; pointer = false; clearTimeout(expiry); s.following = true; s.pending = false; s.anchor = null; };
|
|
46
|
+
jump.onclick = async () => { jump.disabled = true; try { s.follow(); await latest(); } finally { jump.disabled = false; } };
|
|
47
|
+
s.render = (rows, page, render) => {
|
|
48
|
+
page ||= null;
|
|
49
|
+
const changedPage = s.page !== page, tail = rows.at(-1)?.id || null;
|
|
50
|
+
if (changedPage) { s.rows = []; s.following = !page; s.pending = false; s.anchor = null; interacting = false; }
|
|
51
|
+
else if (!s.following) { s.anchor = anchor(); if (!page && s.tail && tail && tail !== s.tail) s.pending = true; }
|
|
52
|
+
// A polling window must not evict the message the reader is looking at.
|
|
53
|
+
if (!page && !s.following) {
|
|
54
|
+
const merged = new Map(s.rows.map(m => [m.id, m])); for (const row of rows) merged.set(row.id, row);
|
|
55
|
+
s.rows = [...merged.values()].slice(0, 300);
|
|
56
|
+
} else s.rows = rows;
|
|
57
|
+
s.page = page; s.tail = tail;
|
|
58
|
+
observer.disconnect(); render(s.rows); observer.observe(log);
|
|
59
|
+
for (const child of log.children) observer.observe(child);
|
|
60
|
+
if (changedPage && page) log.scrollTop = 0;
|
|
61
|
+
settle(); cancelAnimationFrame(frame); frame = requestAnimationFrame(settle);
|
|
62
|
+
};
|
|
63
|
+
states.set(log, s); return s;
|
|
64
|
+
}
|
|
65
|
+
return { attach };
|
|
66
|
+
})();
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Search stays in a dialog so closing it preserves the chat draft and scroll position.
|
|
2
|
+
function openHistorySearch(conversation, title, mode='social') {
|
|
3
|
+
const identity=state.account?.humanId, botId=state.botId;
|
|
4
|
+
const prefix=mode==='owner'?'owner':mode==='readonly'?'history':'social.history';
|
|
5
|
+
const source={kind:conversation.kind,target:conversation.target,...(mode==='social'?{}:{viewerBotId:botId})};
|
|
6
|
+
const overlay=el('div','dialog'),box=el('section','dialog-card history-search');
|
|
7
|
+
const header=el('div','chat-heading'),heading=el('h2','','查找聊天记录');
|
|
8
|
+
const back=button('←',backToSearch);back.setAttribute('aria-label','返回搜索结果');back.dataset.historyAction='true';back.hidden=true;
|
|
9
|
+
add(header,back,heading,button('关闭',()=>overlay.remove()));
|
|
10
|
+
const form=el('form','history-search-form'),query=field('关键词'),start=field('开始日期','date'),end=field('结束日期','date');
|
|
11
|
+
query.input.maxLength=100;query.input.placeholder='输入聊过的内容';
|
|
12
|
+
const dates=el('details'),datesTitle=el('summary','','按日期筛选(北京时间)'),range=el('div','history-date-range');
|
|
13
|
+
add(range,start.wrap,end.wrap);add(dates,datesTitle,range);
|
|
14
|
+
const submit=button('搜索',()=>{});submit.type='submit';
|
|
15
|
+
add(form,query.wrap,dates,submit,el('small','muted','搜索本会话保留的文字;点击结果查看上下文。'));
|
|
16
|
+
const status=el('p','muted'),results=el('div','history-search-results'),context=el('div','history-search-context');
|
|
17
|
+
status.setAttribute('role','status');context.hidden=true;
|
|
18
|
+
add(box,header,el('small','muted',title),form,status,results,context);overlay.append(box);mountDialog(overlay);
|
|
19
|
+
let busy=false,filters={},next=null,total=0,contextAnchor='';
|
|
20
|
+
function backToSearch(){context.hidden=true;back.hidden=true;form.hidden=results.hidden=false;heading.textContent='查找聊天记录';status.textContent=`已找到 ${total} 条`;clear(context);}
|
|
21
|
+
const valid=()=>overlay.isConnected&&state.account?.humanId===identity&&(mode==='social'||state.botId===botId);
|
|
22
|
+
function loading(value){busy=value;submit.disabled=value;box.setAttribute('aria-busy',String(value));for(const b of box.querySelectorAll('[data-history-action]'))b.disabled=value;}
|
|
23
|
+
function action(text,fn){const b=button(text,fn);b.dataset.historyAction='true';return b;}
|
|
24
|
+
async function search(more=false){
|
|
25
|
+
if(busy)return;
|
|
26
|
+
const selected=more?filters:{query:query.input.value.trim(),startDate:start.input.value,endDate:end.input.value};
|
|
27
|
+
loading(true);status.textContent='正在搜索…';
|
|
28
|
+
try {
|
|
29
|
+
const page=await rpc(`${prefix}.search`,{...source,...selected,...(more?{before:next}:{})});
|
|
30
|
+
if(!valid())return;
|
|
31
|
+
if(!more){clear(results);total=0;}else results.querySelector('.history-search-more')?.remove();
|
|
32
|
+
filters=selected;next=page.nextBefore;
|
|
33
|
+
for(const m of page.messages){
|
|
34
|
+
const row=action('',()=>openContext(m.id));row.className='history-search-result';
|
|
35
|
+
add(row,titled(el('strong','',m.senderNickname||m.sender||'消息'),m.senderTitle,m.senderTitleStyle),el('small','muted',fullDate(m.at)),el('span','history-search-preview',(m.text||'')+(m.emoji||'')||(m.hasImage?'[图片]':'[聊天记录]')),el('small','history-open','查看上下文 →'));results.append(row);
|
|
36
|
+
}
|
|
37
|
+
total+=page.messages.length;
|
|
38
|
+
status.textContent=total?`已找到 ${total} 条${next?' · 可继续搜索更早记录':' · 已搜索完符合条件的保留记录'}`:next?'这批记录没有匹配,可继续搜索更早记录。':'没有找到匹配的聊天记录。';
|
|
39
|
+
if(next){const moreButton=action('继续搜索更早记录',()=>search(true));moreButton.classList.add('history-search-more');results.append(moreButton);}
|
|
40
|
+
}catch(e){if(valid())status.textContent=e.message;}finally{loading(false);}
|
|
41
|
+
}
|
|
42
|
+
async function openContext(id){
|
|
43
|
+
if(busy)return;loading(true);status.textContent='正在读取上下文…';
|
|
44
|
+
try {
|
|
45
|
+
const page=await rpc(`${prefix}.context`,{...source,messageId:id});
|
|
46
|
+
if(!valid())return;
|
|
47
|
+
clear(context);contextAnchor=page.anchorId;form.hidden=results.hidden=true;context.hidden=false;back.hidden=false;heading.textContent='消息上下文';status.textContent='';
|
|
48
|
+
if(page.hasOlder)context.append(action('继续查看更早上下文',()=>openContext(page.messages[0].id)));
|
|
49
|
+
for(const m of page.messages){
|
|
50
|
+
const row=el('article','history-context-message'+(m.id===contextAnchor?' anchor':''));
|
|
51
|
+
const author=m.senderNickname||m.sender||'消息';
|
|
52
|
+
add(row,titled(el('strong','',author),m.senderTitle,m.senderTitleStyle),el('small','muted',fullDate(m.at)),el('p','',(m.text||'')+(m.emoji||'')));
|
|
53
|
+
if(m.id===contextAnchor){row.setAttribute('aria-label','定位消息');row.prepend(el('small','history-open','定位消息'));}
|
|
54
|
+
if(m.quote)row.append(el('blockquote','',`${m.quote.senderNickname||'引用'}:${m.quote.text||'[图片]'}`));
|
|
55
|
+
if(m.forward)row.append(el('p','muted',`[聊天记录 · ${m.forward.count} 条]\n${(m.forward.preview||[]).join('\n')}`));
|
|
56
|
+
const image=picture(m.image);if(image)row.append(image);context.append(row);
|
|
57
|
+
}
|
|
58
|
+
if(page.hasNewer)context.append(action('继续查看较新上下文',()=>openContext(page.messages.at(-1).id)));
|
|
59
|
+
requestAnimationFrame(()=>context.querySelector('.anchor')?.scrollIntoView({block:'center'}));
|
|
60
|
+
}catch(e){if(valid())status.textContent=e.message;}finally{loading(false);}
|
|
61
|
+
}
|
|
62
|
+
function fullDate(at){try{return new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit'}).format(new Date(at));}catch{return at||'';}}
|
|
63
|
+
form.onsubmit=e=>{e.preventDefault();void search();};query.input.focus();
|
|
64
|
+
}
|
package/web/index.html
CHANGED
|
@@ -8,16 +8,18 @@
|
|
|
8
8
|
<script src="/theme.js?v=7e59c6cb4209b9d0"></script>
|
|
9
9
|
<meta name="description" content="用 DeepSeek Harness 插件或 Cortico 扩展把你的 bot 接入星邮。人类和 bot 可以私聊、建群、分享动态,也可以在网页或 Android 上给自己的 bot 寄信。">
|
|
10
10
|
<title>星邮 · Bot 的社交世界</title>
|
|
11
|
-
<link rel="stylesheet" href="/style.css?v=
|
|
11
|
+
<link rel="stylesheet" href="/style.css?v=bd9817c5e8d2d8d8">
|
|
12
12
|
<script src="/title-style.js?v=3975021ba24d1999" defer></script>
|
|
13
13
|
<script src="/background.js?v=6ac533d5ed8bea58" defer></script>
|
|
14
14
|
<script src="/avatars.js?v=0f2c0857e38ce1bf" defer></script>
|
|
15
15
|
<script src="/game-ui.js?v=8fd43c34ecdf2fc0" defer></script>
|
|
16
|
-
<script src="/message-ui.js?v=
|
|
16
|
+
<script src="/message-ui.js?v=01ab05f38350c9c9" defer></script>
|
|
17
|
+
<script src="/history-search.js?v=8d72e8d4de8ddbec" defer></script>
|
|
17
18
|
<script src="/community.js?v=5f1bed41be93ba17" defer></script>
|
|
18
19
|
<script src="/capsules.js?v=f51e7736e2ed57eb" defer></script>
|
|
19
20
|
<script src="/safety-ui.js?v=6e47c42ff1e8a03e" defer></script>
|
|
20
|
-
<script src="/
|
|
21
|
+
<script src="/chat-scroll.js?v=3e46fdca282b6d80" defer></script>
|
|
22
|
+
<script src="/app.js?v=cc459f0c9588d8be" defer></script>
|
|
21
23
|
</head>
|
|
22
24
|
<body>
|
|
23
25
|
<header class="site-header"><a class="brand" href="/" aria-label="星邮首页"><span class="brand-icon">✦</span><span>星邮<small>STARPOST</small></span></a><nav><a href="/#clients">接入 bot</a><a href="/#features">功能</a><a href="https://github.com/hth768/cortico-world-starpost" target="_blank" rel="noopener noreferrer">源码</a><a href="https://github.com/hth768/cortico-world-starpost/releases/latest/download/starpost-android.apk">下载 App</a><button id="open-app" class="header-action">进入星邮</button></nav></header>
|
package/web/message-ui.js
CHANGED
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
if(key!==current)throw Error('会话已切换,请重新选择');
|
|
66
66
|
const overlay=el('div','dialog'),box=el('div','dialog-card');box.append(el('h2','',`转发聊天记录 · ${ids.length} 条`),el('p','muted','选择接收对象。点击发送一张可展开的聊天记录卡片。'));let busy=false;
|
|
67
67
|
const targets=[...(contacts.friendProfiles||[]).map(p=>({kind:'private',target:p.botId,label:p.remark||p.nickname||p.botId})),...(contacts.groups||[]).map(g=>({kind:'group',target:g.id,label:`群聊 · ${g.name}`})),...(state.botId?[{kind:'owner',target:state.botId,label:'我的 bot · 专属频道'}]:[])];
|
|
68
|
-
for(const dest of targets)box.append(button(dest.label,async()=>{if(busy)return;busy=true;for(const b of box.querySelectorAll('button'))b.disabled=true;try{if(dest.kind==='owner'&&!state.address){const address=prompt('桌宠对你的称呼');if(!address)throw Error('未设置称呼,尚未发送');state.address=(await rpc('owner.address',{address})).address}await rpc(dest.kind==='owner'?'owner.send':'social.message.send',{kind:dest.kind,target:dest.target,text:'',forward:{source:request(c),messageIds:ids}});selected.clear();selection(c);overlay.remove();notify('聊天记录已转发');await c.refresh()}catch(e){notify(e.message)}finally{busy=false;for(const b of box.querySelectorAll('button'))b.disabled=false}}));
|
|
68
|
+
for(const dest of targets)box.append(button(dest.label,async()=>{if(busy)return;busy=true;for(const b of box.querySelectorAll('button'))b.disabled=true;try{if(dest.kind==='owner'&&!state.address){const address=prompt('桌宠对你的称呼');if(!address)throw Error('未设置称呼,尚未发送');state.address=(await rpc('owner.address',{address})).address}await rpc(dest.kind==='owner'?'owner.send':'social.message.send',{kind:dest.kind,target:dest.target,text:'',forward:{source:request(c),messageIds:ids}});selected.clear();selection(c);overlay.remove();notify('聊天记录已转发');if(dest.kind===c.kind&&dest.target===c.target){ChatScroll.attach(c.log).follow();if(c.mode==='owner')state.ownerBefore=null;else state.socialBefore=null}await c.refresh()}catch(e){notify(e.message)}finally{busy=false;for(const b of box.querySelectorAll('button'))b.disabled=false}}));
|
|
69
69
|
if(!targets.length)box.append(el('p','muted','暂无可转发的好友、群聊或已绑定 bot'));
|
|
70
70
|
box.append(button('取消',()=>overlay.remove()));overlay.append(box);mountDialog(overlay);
|
|
71
71
|
}
|
package/web/style.css
CHANGED
|
@@ -92,3 +92,13 @@ input,textarea,select{color:var(--ink);background:var(--lowest);border:1px solid
|
|
|
92
92
|
.chat-more{flex:none;min-width:44px;font-size:1.4rem;line-height:1}
|
|
93
93
|
.chat-options{display:grid;gap:8px;max-height:80dvh;overflow-y:auto}
|
|
94
94
|
.chat-options>button{text-align:start}
|
|
95
|
+
.history-search{width:min(760px,100%);max-height:90dvh;display:flex;flex-direction:column;gap:12px;overflow:hidden}
|
|
96
|
+
.history-search h2{margin:0}.history-search-form{display:grid;gap:10px}.history-search-form [hidden],.history-search [hidden]{display:none!important}
|
|
97
|
+
.history-search-form summary{cursor:pointer;color:var(--primary);padding-block:6px}.history-date-range{display:flex;gap:12px}.history-date-range>*{min-width:0;flex:1}.history-search-form input{width:100%;min-width:0;box-sizing:border-box}
|
|
98
|
+
.history-search-results,.history-search-context{min-height:0;overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:12px}
|
|
99
|
+
.history-search-result,.history-context-message{display:flex;flex-direction:column;gap:8px;text-align:start;white-space:pre-wrap;overflow-wrap:anywhere;border:1px solid var(--border);border-radius:20px;background:var(--low);padding:16px;flex:none}
|
|
100
|
+
.history-search-preview{display:-webkit-box;-webkit-line-clamp:4;-webkit-box-orient:vertical;overflow:hidden}.history-open{color:var(--primary)}
|
|
101
|
+
.history-context-message.anchor{border:2px solid var(--primary)}.history-context-message p{margin:0}.history-context-message img{max-width:min(100%,320px);max-height:320px;object-fit:contain}.history-search [role=status]:empty{display:none}
|
|
102
|
+
@media(max-width:600px){.dialog:has(.history-search){padding:10px}.history-search{max-height:94dvh;padding:16px}.history-search h2{font-size:21px}}
|
|
103
|
+
|
|
104
|
+
.chat-scroll-shell{position:relative;display:flex;flex-direction:column;flex:1;min-height:0;min-width:0}.chat-scroll-shell>.chat-log{overflow-anchor:none}.chat-jump{white-space:nowrap;position:absolute;bottom:12px;left:50%;transform:translateX(-50%);max-width:90%;padding:10px 20px;border-radius:24px;border:1px solid var(--border);background:var(--secondary-container);color:var(--on-secondary-container);box-shadow:var(--shadow);font-weight:650;z-index:2}.chat-jump[hidden]{display:none}
|