@alexsun-top/opencode-chat-room 0.7.5 → 0.7.6
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 +14 -0
- package/README.md +5 -5
- package/README.zh-CN.md +5 -5
- package/cli.ts +20 -0
- package/dist/cli.js +18 -0
- package/package.json +1 -1
- package/server/assets/chat/doc-preview.js +113 -0
- package/server/assets/chat/events.js +6 -0
- package/server/assets/chat/files.js +14 -6
- package/server/assets/chat/index.js +2 -0
- package/server/assets/chat/locales/de.js +3 -3
- package/server/assets/chat/locales/es.js +3 -3
- package/server/assets/chat/locales/fr.js +3 -3
- package/server/assets/chat/locales/it.js +3 -3
- package/server/assets/chat/locales/ja.js +3 -3
- package/server/assets/chat/locales/ko.js +3 -3
- package/server/assets/chat/markdown.js +12 -4
- package/server/assets/chat/palette.js +9 -5
- package/server/assets/chat/state.js +6 -6
- package/server/assets/chat/system-messages.js +7 -1
- package/server/assets/doc-preview.css +158 -0
- package/server/assets/edit-room.css +8 -0
- package/server/assets/settings.css +9 -2
- package/server/chat.html +33 -15
- package/server/sw.js +1 -0
- package/src/tui/app.mjs +16 -1
- package/src/tui/http.mjs +109 -10
- package/src/tui/info-app.mjs +435 -0
- package/src/tui/info-content.mjs +198 -0
- package/src/tui/join-app.mjs +71 -0
- package/src/tui/main.mjs +23 -4
- package/src/tui/markdown.mjs +269 -0
- package/src/tui/message-app.mjs +177 -0
- package/src/tui/message-view.mjs +128 -0
- package/src/tui/palette-app.mjs +85 -9
- package/src/tui/palette.mjs +17 -2
- package/src/tui/reminder-app.mjs +189 -0
- package/src/tui/room-settings-app.mjs +249 -0
- package/src/tui/ui-content.mjs +136 -93
- package/src/tui/ui-overlay-view.mjs +255 -0
- package/src/tui/ui-view.mjs +2 -190
- package/src/tui/ui.mjs +103 -1
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Pure formatting for the CLI parity commands. No terminal or network code, so
|
|
2
|
+
// the row text and the settings redaction can be checked directly in tests.
|
|
3
|
+
import { sanitizeText } from "./messages.mjs";
|
|
4
|
+
|
|
5
|
+
const oneLine = (value, max = 100) => {
|
|
6
|
+
const text = sanitizeText(value).replace(/\s+/g, " ").trim();
|
|
7
|
+
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
function timeLabel(value) {
|
|
11
|
+
const ms = typeof value === "number" ? value : Date.parse(String(value ?? ""));
|
|
12
|
+
if (!Number.isFinite(ms)) return "unknown time";
|
|
13
|
+
const date = new Date(ms);
|
|
14
|
+
const pad = (part) => String(part).padStart(2, "0");
|
|
15
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function formatBytes(size) {
|
|
19
|
+
const bytes = Number(size);
|
|
20
|
+
if (!Number.isFinite(bytes) || bytes < 0) return "?";
|
|
21
|
+
if (bytes < 1024) return `${Math.round(bytes)} B`;
|
|
22
|
+
const units = ["KB", "MB", "GB", "TB"];
|
|
23
|
+
let value = bytes / 1024;
|
|
24
|
+
let unit = 0;
|
|
25
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
26
|
+
value /= 1024;
|
|
27
|
+
unit += 1;
|
|
28
|
+
}
|
|
29
|
+
return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[unit]}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function memberRows(members, selfID) {
|
|
33
|
+
return (Array.isArray(members) ? members : []).map((member) => {
|
|
34
|
+
const self = Boolean(selfID) && member.sessionID === selfID;
|
|
35
|
+
const name = sanitizeText(member.name || member.sessionID || "?");
|
|
36
|
+
const type = member.type === "agent" ? "agent" : "human";
|
|
37
|
+
const activity = sanitizeText(member.activity?.state || "unknown");
|
|
38
|
+
return {
|
|
39
|
+
name: `${self ? "●" : "○"} ${name}${self ? " (you)" : ""} · member · ${type} · ${activity}`,
|
|
40
|
+
value: String(member.sessionID ?? name),
|
|
41
|
+
};
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function announcementRows(announcements) {
|
|
46
|
+
return (Array.isArray(announcements) ? announcements : []).map((item) => ({
|
|
47
|
+
name: `${sanitizeText(item.name)} · updated ${timeLabel(item.updatedAt)}`,
|
|
48
|
+
value: String(item.name),
|
|
49
|
+
content: String(item.content ?? ""),
|
|
50
|
+
updatedAt: item.updatedAt,
|
|
51
|
+
}));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function questionRows(open, messages = []) {
|
|
55
|
+
const rows = [];
|
|
56
|
+
const seen = new Set();
|
|
57
|
+
for (const question of Array.isArray(open) ? open : []) {
|
|
58
|
+
seen.add(question.id);
|
|
59
|
+
const answered = Boolean(question.answeredByMessageID);
|
|
60
|
+
rows.push({
|
|
61
|
+
name: `${answered ? "✓" : "?"} ${sanitizeText(question.senderId || "?")}: ${oneLine(question.text)}${answered ? " (answered)" : ""}`,
|
|
62
|
+
value: String(question.id),
|
|
63
|
+
text: String(question.text ?? ""),
|
|
64
|
+
open: !answered,
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
for (const message of Array.isArray(messages) ? messages : []) {
|
|
68
|
+
if (!message?.isQuestion || !message.answeredByMessageID || seen.has(message.id)) continue;
|
|
69
|
+
seen.add(message.id);
|
|
70
|
+
rows.push({
|
|
71
|
+
name: `✓ ${sanitizeText(message.senderId || "?")}: ${oneLine(message.text)} (answered)`,
|
|
72
|
+
value: String(message.id),
|
|
73
|
+
open: false,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return rows;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function fileRows(resources) {
|
|
80
|
+
return (Array.isArray(resources) ? resources : []).map((item) => ({
|
|
81
|
+
name: `${sanitizeText(item.name)} · ${formatBytes(item.size)} · ${sanitizeText(item.uploaderName || item.uploaderSessionID || "unknown")} · ${timeLabel(item.createdAt)}`,
|
|
82
|
+
value: String(item.id),
|
|
83
|
+
resource: item,
|
|
84
|
+
}));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export function joinRequestRows(requests) {
|
|
88
|
+
return (Array.isArray(requests) ? requests : []).map((item) => ({
|
|
89
|
+
name: `${sanitizeText(item.name || item.participantId || "?")} · ${item.isAgent ? "Agent" : "Human"} · ${timeLabel(item.createdAt)}`,
|
|
90
|
+
value: String(item.sessionID),
|
|
91
|
+
request: item,
|
|
92
|
+
}));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function reminderRows(reminders) {
|
|
96
|
+
return (Array.isArray(reminders) ? reminders : []).map((item) => {
|
|
97
|
+
const schedule = item.schedule?.type === "cron"
|
|
98
|
+
? `cron ${sanitizeText(item.schedule.expression)} (${sanitizeText(item.schedule.timezone || "server")})`
|
|
99
|
+
: `once ${timeLabel(Date.parse(item.schedule?.at ?? ""))}`;
|
|
100
|
+
const next = typeof item.nextRunAt === "string" ? timeLabel(Date.parse(item.nextRunAt)) : timeLabel(item.nextRunAt);
|
|
101
|
+
return {
|
|
102
|
+
name: `${item.paused ? "⏸" : "●"} ${oneLine(item.text)} · ${schedule} · next ${next}`,
|
|
103
|
+
value: String(item.id),
|
|
104
|
+
paused: Boolean(item.paused),
|
|
105
|
+
text: String(item.text ?? ""),
|
|
106
|
+
schedule: item.schedule,
|
|
107
|
+
nextRunAt: item.nextRunAt,
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function timezoneOrThrow(value) {
|
|
113
|
+
try {
|
|
114
|
+
new Intl.DateTimeFormat("en-US", { timeZone: value });
|
|
115
|
+
return value;
|
|
116
|
+
} catch {
|
|
117
|
+
throw new Error(`invalid timezone: ${value}`);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Parse "once <ISO datetime> [timezone]" or "cron <5 fields> [timezone]". */
|
|
122
|
+
export function parseReminderSchedule(input) {
|
|
123
|
+
const parts = String(input ?? "").trim().split(/\s+/);
|
|
124
|
+
const kind = parts.shift()?.toLowerCase();
|
|
125
|
+
if (kind === "cron") {
|
|
126
|
+
if (parts.length < 5) throw new Error("cron needs 5 fields, for example: cron 0 9 * * *");
|
|
127
|
+
if (parts.length > 6) throw new Error("cron accepts 5 fields plus an optional timezone");
|
|
128
|
+
const expression = parts.slice(0, 5).join(" ");
|
|
129
|
+
const timezone = parts[5] ? timezoneOrThrow(parts[5]) : undefined;
|
|
130
|
+
return { type: "cron", expression, ...(timezone ? { timezone } : {}) };
|
|
131
|
+
}
|
|
132
|
+
if (kind === "once") {
|
|
133
|
+
if (!parts.length) throw new Error("once needs an ISO datetime, for example: once 2026-11-23T09:00");
|
|
134
|
+
if (parts.length > 2) throw new Error("once accepts an ISO datetime plus an optional timezone");
|
|
135
|
+
const at = parts[0];
|
|
136
|
+
if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/.test(at) || !Number.isFinite(Date.parse(at))) {
|
|
137
|
+
throw new Error("once needs an ISO datetime, for example: 2026-11-23T09:00");
|
|
138
|
+
}
|
|
139
|
+
const timezone = parts[1] ? timezoneOrThrow(parts[1]) : undefined;
|
|
140
|
+
if (Date.parse(at) <= Date.now()) throw new Error("once datetime must be in the future");
|
|
141
|
+
return { type: "once", at, ...(timezone ? { timezone } : {}) };
|
|
142
|
+
}
|
|
143
|
+
throw new Error('schedule must start with "once" or "cron"');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function safeValue(value, token) {
|
|
147
|
+
let text = String(value ?? "");
|
|
148
|
+
try {
|
|
149
|
+
const parsed = new URL(text);
|
|
150
|
+
if (parsed.username || parsed.password) {
|
|
151
|
+
parsed.username = "";
|
|
152
|
+
parsed.password = "";
|
|
153
|
+
text = parsed.toString().replace(/\/$/, "");
|
|
154
|
+
}
|
|
155
|
+
} catch {
|
|
156
|
+
// Not a URL: keep the string.
|
|
157
|
+
}
|
|
158
|
+
return token ? text.split(token).join("***") : text;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function settingsMarkdown(settings = {}) {
|
|
162
|
+
const token = settings.token ? String(settings.token) : "";
|
|
163
|
+
const lines = [
|
|
164
|
+
`- **Server**: ${safeValue(settings.server || "not set", token)}`,
|
|
165
|
+
`- **Participant**: ${safeValue(settings.participant || "?", token)}`,
|
|
166
|
+
`- **Session file**: ${safeValue(settings.sessionFile || "unknown", token)}`,
|
|
167
|
+
`- **Config file**: ${safeValue(settings.configFile || "none (environment only)", token)}`,
|
|
168
|
+
`- **Theme**: ${safeValue(settings.theme || "dark", token)}`,
|
|
169
|
+
`- **Delivery**: server long-poll, ${Math.round((settings.pollTimeoutMs ?? 20000) / 1000)}s hold`,
|
|
170
|
+
`- **Request timeout**: ${Math.round((settings.requestTimeoutMs ?? 10000) / 1000)}s`,
|
|
171
|
+
`- **Token**: ${token ? "set (redacted)" : "not set"}`,
|
|
172
|
+
];
|
|
173
|
+
return lines.join("\n");
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function roomSettingsMarkdown(room = {}, { participant, sessionID, canEdit = false, agentName = "" } = {}) {
|
|
177
|
+
const owner = Boolean(participant) && room.ownerId === participant;
|
|
178
|
+
const admin = owner || (room.adminIds ?? []).includes(participant);
|
|
179
|
+
const agentAdmin = Boolean(room.adminSessionID) && room.adminSessionID === sessionID;
|
|
180
|
+
const role = owner ? "owner" : admin ? "admin" : agentAdmin ? "management agent" : "member";
|
|
181
|
+
const policy = room.joinPolicy === "approval" ? "approval" : "open";
|
|
182
|
+
const description = room.description ? oneLine(room.description, 300) : "not set";
|
|
183
|
+
const admins = (room.adminIds ?? []).filter(Boolean).join(", ") || "none";
|
|
184
|
+
const successor = room.successorId || "none";
|
|
185
|
+
const management = room.adminSessionID ? (agentName || room.adminSessionID) : "none";
|
|
186
|
+
return [
|
|
187
|
+
`- **Name**: ${oneLine(room.name || "?", 80)}`,
|
|
188
|
+
`- **Description**: ${description}`,
|
|
189
|
+
`- **Join policy**: ${policy}`,
|
|
190
|
+
`- **Kind**: ${room.kind === "direct" ? "direct" : "group"}`,
|
|
191
|
+
`- **Owner**: ${oneLine(room.ownerId || "?", 80)}`,
|
|
192
|
+
`- **Admins**: ${admins}`,
|
|
193
|
+
`- **Successor**: ${successor}`,
|
|
194
|
+
`- **Management agent**: ${management}`,
|
|
195
|
+
`- **Your role**: ${role}`,
|
|
196
|
+
`- **Editing**: ${canEdit ? "available" : "read-only"}`,
|
|
197
|
+
].join("\n");
|
|
198
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// Pending join-request review for the current room. Reuses the info/confirm
|
|
2
|
+
// overlay and maps 403s to the server's reviewer rule in plain language.
|
|
3
|
+
import { joinRequestRows } from "./info-content.mjs";
|
|
4
|
+
|
|
5
|
+
const ADMIN_ERROR = "only a human administrator or the designated management agent may decide";
|
|
6
|
+
const REVIEW_HINT = "Enter approve · d deny · Esc close";
|
|
7
|
+
const errorText = (error) => (error instanceof Error ? error.message : String(error ?? "unknown error"));
|
|
8
|
+
|
|
9
|
+
export function attachJoinRequests(Class) {
|
|
10
|
+
Object.assign(Class.prototype, {
|
|
11
|
+
openJoinRequests() {
|
|
12
|
+
return this.openInfo("join-requests", "Join requests", REVIEW_HINT, async (room) => {
|
|
13
|
+
try {
|
|
14
|
+
const result = await this.api.joinRequests(room.id, this.sessionID);
|
|
15
|
+
return joinRequestRows(result.requests);
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error?.status === 403) throw new Error(ADMIN_ERROR);
|
|
18
|
+
throw error;
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
},
|
|
22
|
+
|
|
23
|
+
selectedJoinRequest() {
|
|
24
|
+
const palette = this.state.palette;
|
|
25
|
+
if (!palette || palette.mode !== "info" || palette.kind !== "join-requests") return null;
|
|
26
|
+
return this.paletteItems()[palette.selected] ?? null;
|
|
27
|
+
},
|
|
28
|
+
|
|
29
|
+
askJoinDecision(decision) {
|
|
30
|
+
const palette = this.state.palette;
|
|
31
|
+
const request = this.selectedJoinRequest();
|
|
32
|
+
if (!palette || !request) return;
|
|
33
|
+
const name = request.request?.name || request.request?.participantId || request.value;
|
|
34
|
+
palette.mode = "confirm";
|
|
35
|
+
palette.previous = { mode: "info", hint: palette.hint };
|
|
36
|
+
palette.confirm = {
|
|
37
|
+
text: `${decision === "approve" ? "Approve" : "Deny"} "${name}"?`,
|
|
38
|
+
action: `join-${decision}`,
|
|
39
|
+
data: { sessionID: request.value, name },
|
|
40
|
+
};
|
|
41
|
+
palette.error = "";
|
|
42
|
+
palette.hint = "Enter or y confirms · n or Esc cancels";
|
|
43
|
+
this.touch();
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
async runJoinConfirm(confirm) {
|
|
47
|
+
const palette = this.state.palette;
|
|
48
|
+
const room = this.state.current;
|
|
49
|
+
if (!palette || !room) return;
|
|
50
|
+
const decision = confirm.action === "join-approve" ? "approve" : "deny";
|
|
51
|
+
palette.searching = true;
|
|
52
|
+
palette.error = "";
|
|
53
|
+
this.touch();
|
|
54
|
+
try {
|
|
55
|
+
await this.api.decideJoin(room.id, confirm.data.sessionID, this.sessionID, decision);
|
|
56
|
+
this.setStatus(`${decision === "approve" ? "approved" : "denied"} ${confirm.data.name}`, "success");
|
|
57
|
+
await this.openJoinRequests();
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (this.state.palette === palette) {
|
|
60
|
+
palette.mode = "info";
|
|
61
|
+
palette.confirm = null;
|
|
62
|
+
palette.previous = null;
|
|
63
|
+
palette.searching = false;
|
|
64
|
+
palette.hint = REVIEW_HINT;
|
|
65
|
+
palette.error = error?.status === 403 ? ADMIN_ERROR : errorText(error);
|
|
66
|
+
this.touch();
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
package/src/tui/main.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
// CLI entry for `opencode-chat-room cli`. Config, HTTP and session helpers are
|
|
2
2
|
// imported lazily so --help/--version work without a terminal or OpenTUI.
|
|
3
3
|
import { readFileSync } from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
4
5
|
import { createApp } from "./app.mjs";
|
|
5
6
|
|
|
6
7
|
const NAME = "opencode-chat-room cli";
|
|
7
|
-
const FALLBACK_VERSION = "0.7.
|
|
8
|
+
const FALLBACK_VERSION = "0.7.6";
|
|
8
9
|
|
|
9
10
|
export const HELP = `opencode-chat-room cli - terminal client for a chat-room server
|
|
10
11
|
|
|
@@ -24,6 +25,9 @@ A token is never accepted on the command line. See the README for fields.
|
|
|
24
25
|
Keys: arrows select rooms · Enter opens · Tab focuses the composer ·
|
|
25
26
|
PageUp/PageDown scroll · Alt+Home/End jumps · Alt+Space or Ctrl+P opens the
|
|
26
27
|
palette · Ctrl+C quits.
|
|
28
|
+
Type / in an empty composer for commands: members, join requests, announcements,
|
|
29
|
+
questions, files, reminders, room settings, recall/reveal/reply/ask,
|
|
30
|
+
delete room and quit.
|
|
27
31
|
This command needs an interactive terminal.
|
|
28
32
|
`;
|
|
29
33
|
|
|
@@ -56,7 +60,7 @@ function runtimeProblem() {
|
|
|
56
60
|
(bunMajor > 1 || (bunMajor === 1 && (bunMinor > 3 || (bunMinor === 3 && bunPatch >= 14))));
|
|
57
61
|
const nodeSupported = nodeMajor > 26 || (nodeMajor === 26 && nodeMinor >= 4);
|
|
58
62
|
if (typeof globalThis.Deno !== "undefined" || (!bunSupported && !nodeSupported)) {
|
|
59
|
-
return "the terminal client requires Bun 1.3.14+ or Node.js 26.4
|
|
63
|
+
return "the terminal client requires Bun 1.3.14+ or Node.js 26.4+ with --experimental-ffi. Install Bun 1.3.14+ and retry, or use a supported Node.js version.";
|
|
60
64
|
}
|
|
61
65
|
return "";
|
|
62
66
|
}
|
|
@@ -114,7 +118,7 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
114
118
|
let renderer;
|
|
115
119
|
let ui;
|
|
116
120
|
try {
|
|
117
|
-
const [{ resolveTuiConfig }, { loadSession, saveSession }, { createApi }] = await Promise.all([
|
|
121
|
+
const [{ resolveTuiConfig, findTuiConfigFile }, { loadSession, saveSession }, { createApi }] = await Promise.all([
|
|
118
122
|
import("./config.mjs"),
|
|
119
123
|
import("./session.mjs"),
|
|
120
124
|
import("./http.mjs"),
|
|
@@ -149,7 +153,22 @@ export async function main(argv = process.argv.slice(2)) {
|
|
|
149
153
|
targetFps: 30,
|
|
150
154
|
clearOnShutdown: true,
|
|
151
155
|
});
|
|
152
|
-
const app = createApp({
|
|
156
|
+
const app = createApp({
|
|
157
|
+
api,
|
|
158
|
+
sessionID: session.sessionID,
|
|
159
|
+
participant,
|
|
160
|
+
host,
|
|
161
|
+
settings: {
|
|
162
|
+
server: config.url,
|
|
163
|
+
participant,
|
|
164
|
+
sessionFile: config.stateFile,
|
|
165
|
+
configFile: findTuiConfigFile(process.env, process.cwd()) ?? "",
|
|
166
|
+
requestTimeoutMs: config.requestTimeoutMs,
|
|
167
|
+
pollTimeoutMs: 20000,
|
|
168
|
+
token: config.token,
|
|
169
|
+
},
|
|
170
|
+
downloadDir: path.join(process.cwd(), "downloads"),
|
|
171
|
+
});
|
|
153
172
|
ui = createTui(renderer, app);
|
|
154
173
|
await app.init();
|
|
155
174
|
ui.sync();
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// Mention and Markdown helpers shared by the TUI message renderer and tests.
|
|
2
|
+
// Mentions become a private inline-code marker before parsing: default
|
|
3
|
+
// Markdown rendering shows just @name, and paragraphs are upgraded by a custom
|
|
4
|
+
// renderNode to accent styling. Fenced/inline code is never rewritten.
|
|
5
|
+
import {
|
|
6
|
+
StyledText,
|
|
7
|
+
SyntaxStyle,
|
|
8
|
+
TextRenderable,
|
|
9
|
+
bg,
|
|
10
|
+
bold,
|
|
11
|
+
dim,
|
|
12
|
+
fg,
|
|
13
|
+
italic,
|
|
14
|
+
strikethrough,
|
|
15
|
+
underline,
|
|
16
|
+
} from "@opentui/core";
|
|
17
|
+
|
|
18
|
+
export const MENTION_SENTINEL = "\u200B";
|
|
19
|
+
const MENTION_TAG = /^<at>(@[^\n<>`\\]{1,64})<\/at>/u;
|
|
20
|
+
const RESOURCE_MARKER = /\[\[resource:[^\]\s]+\]\]/gi;
|
|
21
|
+
|
|
22
|
+
/** Show attachment markers as a readable label and never leak the UUID. */
|
|
23
|
+
export function formatAttachments(text) {
|
|
24
|
+
const source = String(text ?? "");
|
|
25
|
+
const markers = source.match(RESOURCE_MARKER);
|
|
26
|
+
if (!markers) return source;
|
|
27
|
+
const clean = source
|
|
28
|
+
.replace(RESOURCE_MARKER, " ")
|
|
29
|
+
.replace(/[ \t]+\n/g, "\n")
|
|
30
|
+
.replace(/\n[ \t]+/g, "\n")
|
|
31
|
+
.replace(/[ \t]{2,}/g, " ")
|
|
32
|
+
.trim();
|
|
33
|
+
if (!clean) return "Attachments";
|
|
34
|
+
return `${clean} · Attachments`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function inlineMentions(line) {
|
|
38
|
+
let out = "";
|
|
39
|
+
let index = 0;
|
|
40
|
+
while (index < line.length) {
|
|
41
|
+
if (line[index] === "`") {
|
|
42
|
+
let run = 0;
|
|
43
|
+
while (line[index + run] === "`") run += 1;
|
|
44
|
+
const fence = "`".repeat(run);
|
|
45
|
+
const close = line.indexOf(fence, index + run);
|
|
46
|
+
if (close === -1) {
|
|
47
|
+
out += line.slice(index);
|
|
48
|
+
break;
|
|
49
|
+
}
|
|
50
|
+
out += line.slice(index, close + run);
|
|
51
|
+
index = close + run;
|
|
52
|
+
continue;
|
|
53
|
+
}
|
|
54
|
+
const match = line.slice(index).match(MENTION_TAG);
|
|
55
|
+
if (match) {
|
|
56
|
+
out += `\`${MENTION_SENTINEL}${match[1]}\``;
|
|
57
|
+
index += match[0].length;
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
out += line[index];
|
|
61
|
+
index += 1;
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Rewrite <at>@name</at> in prose, leaving fenced and inline code untouched. */
|
|
67
|
+
export function prepareMarkdown(text) {
|
|
68
|
+
let fence = null;
|
|
69
|
+
return String(text ?? "")
|
|
70
|
+
.split("\n")
|
|
71
|
+
.map((line) => {
|
|
72
|
+
const marker = line.match(/^\s*(`{3,}|~{3,})/);
|
|
73
|
+
if (fence) {
|
|
74
|
+
if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length) fence = null;
|
|
75
|
+
return line;
|
|
76
|
+
}
|
|
77
|
+
if (marker) {
|
|
78
|
+
fence = marker[1];
|
|
79
|
+
return line;
|
|
80
|
+
}
|
|
81
|
+
return inlineMentions(line);
|
|
82
|
+
})
|
|
83
|
+
.join("\n");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function isMentionCode(token) {
|
|
87
|
+
return token?.type === "codespan" && String(token.text ?? "").startsWith(MENTION_SENTINEL);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function containsMention(token) {
|
|
91
|
+
if (!token) return false;
|
|
92
|
+
if (isMentionCode(token)) return true;
|
|
93
|
+
if (Array.isArray(token.tokens) && token.tokens.some(containsMention)) return true;
|
|
94
|
+
return typeof token.raw === "string" && token.raw.includes(MENTION_SENTINEL);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function chunk(text, color, style = {}) {
|
|
98
|
+
let value = fg(color)(text);
|
|
99
|
+
if (style.bold) value = bold(value);
|
|
100
|
+
if (style.italic) value = italic(value);
|
|
101
|
+
if (style.underline) value = underline(value);
|
|
102
|
+
if (style.strikethrough) value = strikethrough(value);
|
|
103
|
+
if (style.bg) value = bg(style.bg)(value);
|
|
104
|
+
if (style.dim) value = dim(value);
|
|
105
|
+
return value;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function inlineTokens(tokens, theme, style = {}) {
|
|
109
|
+
const chunks = [];
|
|
110
|
+
for (const token of tokens ?? []) {
|
|
111
|
+
switch (token.type) {
|
|
112
|
+
case "text":
|
|
113
|
+
case "escape":
|
|
114
|
+
if (Array.isArray(token.tokens) && token.tokens.length) {
|
|
115
|
+
chunks.push(...inlineTokens(token.tokens, theme, style));
|
|
116
|
+
} else {
|
|
117
|
+
chunks.push(chunk(token.text ?? "", style.color ?? theme.text, style));
|
|
118
|
+
}
|
|
119
|
+
break;
|
|
120
|
+
case "strong":
|
|
121
|
+
chunks.push(...inlineTokens(token.tokens, theme, { ...style, bold: true }));
|
|
122
|
+
break;
|
|
123
|
+
case "em":
|
|
124
|
+
chunks.push(...inlineTokens(token.tokens, theme, { ...style, italic: true }));
|
|
125
|
+
break;
|
|
126
|
+
case "del":
|
|
127
|
+
chunks.push(...inlineTokens(token.tokens, theme, { ...style, strikethrough: true }));
|
|
128
|
+
break;
|
|
129
|
+
case "codespan":
|
|
130
|
+
if (isMentionCode(token)) {
|
|
131
|
+
chunks.push(chunk(String(token.text).slice(MENTION_SENTINEL.length), theme.accent, { bold: true }));
|
|
132
|
+
} else {
|
|
133
|
+
chunks.push(chunk(token.text ?? "", theme.text, { ...style, bg: theme.raised }));
|
|
134
|
+
}
|
|
135
|
+
break;
|
|
136
|
+
case "link": {
|
|
137
|
+
chunks.push(...inlineTokens(token.tokens, theme, {
|
|
138
|
+
...style,
|
|
139
|
+
color: theme.accent,
|
|
140
|
+
underline: true,
|
|
141
|
+
}));
|
|
142
|
+
if (token.href) chunks.push(chunk(` (${token.href})`, theme.muted, style));
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
case "image":
|
|
146
|
+
chunks.push(chunk(token.text || "image", theme.muted, style));
|
|
147
|
+
break;
|
|
148
|
+
case "br":
|
|
149
|
+
chunks.push(chunk("\n", theme.text, style));
|
|
150
|
+
break;
|
|
151
|
+
case "list":
|
|
152
|
+
chunks.push(...flattenList(token, theme));
|
|
153
|
+
break;
|
|
154
|
+
case "table":
|
|
155
|
+
chunks.push(...flattenTable(token, theme));
|
|
156
|
+
break;
|
|
157
|
+
case "blockquote":
|
|
158
|
+
chunks.push(chunk("│ ", theme.accent), ...inlineTokens(token.tokens, theme, { ...style, color: theme.muted }));
|
|
159
|
+
break;
|
|
160
|
+
default:
|
|
161
|
+
if (Array.isArray(token.tokens) && token.tokens.length) {
|
|
162
|
+
chunks.push(...inlineTokens(token.tokens, theme, style));
|
|
163
|
+
} else if (typeof token.text === "string" || typeof token.raw === "string") {
|
|
164
|
+
chunks.push(chunk(token.text ?? token.raw, style.color ?? theme.text, style));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return chunks;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function flattenList(token, theme) {
|
|
172
|
+
const chunks = [];
|
|
173
|
+
const items = Array.isArray(token.items) ? token.items : [];
|
|
174
|
+
for (const [index, item] of items.entries()) {
|
|
175
|
+
const marker = token.ordered ? `${(token.start ?? 1) + index}. ` : "• ";
|
|
176
|
+
if (item.task) chunks.push(chunk(item.checked ? "[x] " : "[ ] ", theme.muted));
|
|
177
|
+
chunks.push(chunk(marker, theme.accent), ...inlineTokens(item.tokens, theme));
|
|
178
|
+
chunks.push(chunk("\n", theme.text));
|
|
179
|
+
}
|
|
180
|
+
return chunks;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function flattenTable(token, theme) {
|
|
184
|
+
const chunks = [];
|
|
185
|
+
const rows = [token.header, ...(token.rows ?? [])];
|
|
186
|
+
for (const row of rows) {
|
|
187
|
+
const cells = Array.isArray(row) ? row : [];
|
|
188
|
+
cells.forEach((cell, index) => {
|
|
189
|
+
if (index) chunks.push(chunk(" │ ", theme.muted));
|
|
190
|
+
const tokens = cell?.tokens?.length ? cell.tokens : [{ type: "text", text: cell?.text ?? "" }];
|
|
191
|
+
chunks.push(...inlineTokens(tokens, theme));
|
|
192
|
+
});
|
|
193
|
+
chunks.push(chunk("\n", theme.text));
|
|
194
|
+
}
|
|
195
|
+
return chunks;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function rawMentionText(text) {
|
|
199
|
+
return String(text ?? "")
|
|
200
|
+
.replace(new RegExp("`" + MENTION_SENTINEL + "(@[^`]*)`", "g"), "$1")
|
|
201
|
+
.split(MENTION_SENTINEL)
|
|
202
|
+
.join("");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function mentionText(token, theme) {
|
|
206
|
+
if (token.type === "heading") {
|
|
207
|
+
return [
|
|
208
|
+
chunk(`${"#".repeat(token.depth ?? 1)} `, theme.accent, { bold: true }),
|
|
209
|
+
...inlineTokens(token.tokens, theme, { bold: true }),
|
|
210
|
+
];
|
|
211
|
+
}
|
|
212
|
+
if (token.type === "list") return flattenList(token, theme);
|
|
213
|
+
if (token.type === "table") return flattenTable(token, theme);
|
|
214
|
+
if (token.type === "blockquote") {
|
|
215
|
+
return [chunk("│ ", theme.accent), ...inlineTokens(token.tokens, theme, { color: theme.muted })];
|
|
216
|
+
}
|
|
217
|
+
if (Array.isArray(token.tokens) && token.tokens.length) return inlineTokens(token.tokens, theme);
|
|
218
|
+
return [chunk(rawMentionText(token.raw ?? token.text), theme.text)];
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function inlineChunks(tokens, theme) {
|
|
222
|
+
return inlineTokens(tokens, theme);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function createMentionRenderNode(renderer, theme, baseID) {
|
|
226
|
+
let counter = 0;
|
|
227
|
+
return (token, context) => {
|
|
228
|
+
if (!containsMention(token)) return context.defaultRender();
|
|
229
|
+
const id = `${baseID}-mention-${counter}`;
|
|
230
|
+
counter += 1;
|
|
231
|
+
return new TextRenderable(renderer, {
|
|
232
|
+
id,
|
|
233
|
+
width: "100%",
|
|
234
|
+
flexShrink: 0,
|
|
235
|
+
wrapMode: "word",
|
|
236
|
+
content: new StyledText(mentionText(token, theme)),
|
|
237
|
+
});
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
export function createMarkdownSyntax(theme) {
|
|
242
|
+
return SyntaxStyle.fromStyles({
|
|
243
|
+
default: { fg: theme.text },
|
|
244
|
+
conceal: { fg: theme.faint },
|
|
245
|
+
"markup.heading": { fg: theme.accent, bold: true },
|
|
246
|
+
"markup.strong": { fg: theme.text, bold: true },
|
|
247
|
+
"markup.italic": { fg: theme.text, italic: true },
|
|
248
|
+
"markup.strikethrough": { fg: theme.muted },
|
|
249
|
+
"markup.raw": { fg: theme.accent, bg: theme.raised, bold: true },
|
|
250
|
+
"markup.list": { fg: theme.accent },
|
|
251
|
+
"markup.quote": { fg: theme.muted, italic: true },
|
|
252
|
+
"markup.link": { fg: theme.muted },
|
|
253
|
+
"markup.link.label": { fg: theme.accent, underline: true },
|
|
254
|
+
"markup.link.url": { fg: theme.muted },
|
|
255
|
+
keyword: { fg: theme.accent, bold: true },
|
|
256
|
+
string: { fg: theme.success },
|
|
257
|
+
comment: { fg: theme.muted, italic: true },
|
|
258
|
+
number: { fg: theme.warning },
|
|
259
|
+
constant: { fg: theme.warning },
|
|
260
|
+
function: { fg: theme.text, bold: true },
|
|
261
|
+
type: { fg: theme.warning },
|
|
262
|
+
variable: { fg: theme.text },
|
|
263
|
+
property: { fg: theme.text },
|
|
264
|
+
operator: { fg: theme.muted },
|
|
265
|
+
punctuation: { fg: theme.muted },
|
|
266
|
+
tag: { fg: theme.accent },
|
|
267
|
+
attribute: { fg: theme.warning },
|
|
268
|
+
});
|
|
269
|
+
}
|