Personal Telegram developer console for GitHub

feat: add workspace draft diff and ready flow

davoodmehraban89 committed Oct 3, 2026 at 13:09 UTC 7897123636f48ab75d924439545e20f49402ebdd
1 file changed +181 -5
src/plugins/github/workspace.js
+181 -5
@@ -1,4 +1,10 @@
1 -import { digestText, validateEditableFile } from '../../core/workspace-policy.js';
1 +import {
2 + buildUnifiedDiff,
3 + digestText,
4 + makeTargetBranch,
5 + normalizeCommitMessage,
6 + validateEditableFile
7 +} from '../../core/workspace-policy.js';
8
9 const HANDLE_10 = '[A-Za-z0-9_-]{10}';
10 const escapeHtml = value => String(value ?? '')
@@ -27,13 +33,46 @@ function parseCallback(data) {
33 if (match) return { actionId: 'github.workspace.create', kind: 'edit', refId: match[1] };
34 match = value.match(new RegExp(`^ws:(${HANDLE_10})$`));
35 if (match) return { actionId: 'github.workspace.view', kind: 'workspace', workspaceId: match[1] };
36 + match = value.match(new RegExp(`^wtext:(${HANDLE_10})$`));
37 + if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'draft' };
38 + match = value.match(new RegExp(`^wmsg:(${HANDLE_10})$`));
39 + if (match) return { actionId: 'github.workspace.input.prepare', kind: 'input', workspaceId: match[1], mode: 'commit_message' };
40 + match = value.match(new RegExp(`^wdiff:(${HANDLE_10})$`));
41 + if (match) return { actionId: 'github.workspace.diff', kind: 'diff', workspaceId: match[1] };
42 + match = value.match(new RegExp(`^wready:(${HANDLE_10})$`));
43 + if (match) return { actionId: 'github.workspace.ready', kind: 'ready', workspaceId: match[1] };
44 + match = value.match(new RegExp(`^wcancel:(${HANDLE_10})$`));
45 + if (match) return { actionId: 'github.workspace.cancel', kind: 'cancel', workspaceId: match[1] };
46 return null;
47 }
48
49 +function workspaceButtons(workspace) {
50 + return [
51 + [
52 + { text: '📝 متن Draft', callback_data: `wtext:${workspace.id}` },
53 + { text: '✍️ پیام Commit', callback_data: `wmsg:${workspace.id}` }
54 + ],
55 + [
56 + { text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` },
57 + { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }
58 + ],
59 + [
60 + { text: '🗑 لغو Draft', callback_data: `wcancel:${workspace.id}` },
61 + { text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }
62 + ]
63 + ];
64 +}
65 +
66 export function createWorkspaceController({ github, workspaces } = {}) {
67 if (!github) throw new Error('Workspace controller requires GitHub service');
68 if (!workspaces) throw new Error('Workspace controller requires durable workspace store');
69
70 + const requireWorkspace = async (workspaceId, ownerId) => {
71 + const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
72 + if (!workspace) throw new Error('Workspace not found or expired');
73 + return workspace;
74 + };
75 +
76 const renderDirectory = async (repoId, path, ownerId) => {
77 const [repo, items] = await Promise.all([
78 github.getRepository(repoId),
@@ -52,7 +91,7 @@ export function createWorkspaceController({ github, workspaces } = {}) {
91 callback_data: `wnav:${handles[index].refId}`
92 }]);
93 rows.push([
55 - { text: '🔄 بروزرسانی', callback_data: path ? `files:${repoId}` : `files:${repoId}` },
94 + { text: '🔄 بروزرسانی', callback_data: `files:${repoId}` },
95 { text: '📦 پروژه', callback_data: `repo:${repoId}` }
96 ]);
97 return {
@@ -113,10 +152,133 @@ export function createWorkspaceController({ github, workspaces } = {}) {
152 };
153
154 const renderWorkspace = async (workspaceId, ownerId) => {
116 - const workspace = await workspaces.getWorkspace({ ownerId, workspaceId });
117 - if (!workspace) throw new Error('Workspace not found or expired');
155 + const workspace = await requireWorkspace(workspaceId, ownerId);
156 + const changed = workspace.draftText !== workspace.originalText;
157 + const commitMessage = workspace.commitMessage
158 + ? `<code>${escapeHtml(short(workspace.commitMessage, 120))}</code>`
159 + : '<i>ثبت نشده</i>';
160 + return {
161 + text: `📝 <b>Repository Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>\nتغییر محلی: <b>${changed ? 'دارد' : 'ندارد'}</b>\nپیام Commit: ${commitMessage}\n\nتا قبل از تأیید نهایی، هیچ تغییری در GitHub انجام نمی‌شود.`,
162 + reply_markup: { inline_keyboard: workspaceButtons(workspace) }
163 + };
164 + };
165 +
166 + const prepareInput = async (workspaceId, mode, ownerId) => {
167 + const workspace = await requireWorkspace(workspaceId, ownerId);
168 + await workspaces.setPendingInput({ ownerId, workspaceId, mode });
169 + const draftMode = mode === 'draft';
170 return {
119 - text: `📝 <b>Repository Workspace</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nوضعیت: <b>${escapeHtml(workspace.state || 'DRAFT')}</b>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha || '').slice(0, 10))}</code>`,
171 + text: draftMode
172 + ? `📝 <b>متن جدید Draft را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nکل محتوای فایل جایگزین می‌شود. سقف: 3,000 کاراکتر Unicode و 12,000 بایت UTF-8. پیام بعدی فقط یک‌بار مصرف می‌شود.`
173 + : `✍️ <b>پیام Commit را ارسال کنید</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n\nپیام باید غیرخالی و حداکثر 120 کاراکتر باشد. پیام بعدی فقط یک‌بار مصرف می‌شود.`,
174 + reply_markup: { inline_keyboard: [[{ text: '↩️ بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
175 + };
176 + };
177 +
178 + const applyPendingInput = async ({ pending, text }, ownerId) => {
179 + const workspaceId = String(pending?.workspaceId || '');
180 + const mode = String(pending?.mode || '');
181 + if (!new RegExp(`^${HANDLE_10}$`).test(workspaceId) || !['draft', 'commit_message'].includes(mode)) {
182 + throw new Error('Pending workspace input is invalid');
183 + }
184 +
185 + const consumed = await workspaces.consumePendingInput({ ownerId, workspaceId, mode });
186 + if (!consumed) throw new Error('Pending workspace input was already consumed or expired');
187 + const workspace = await requireWorkspace(workspaceId, ownerId);
188 +
189 + if (mode === 'draft') {
190 + const policy = validateEditableFile({ path: workspace.path, text });
191 + if (!policy.editable) {
192 + return {
193 + text: `⚠️ <b>Draft تغییر نکرد</b>\n${escapeHtml(policy.reason || 'متن ارسال‌شده مجاز نیست.')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «متن Draft» را بزنید.`,
194 + reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
195 + };
196 + }
197 + const digest = await digestText(policy.text);
198 + const updated = await workspaces.updateDraft({ ownerId, workspaceId, text: policy.text, digest });
199 + return {
200 + text: `✅ <b>Draft محلی ذخیره شد</b>\nفایل: <code>${escapeHtml(updated.path)}</code>\nکاراکتر: <b>${policy.charLength}</b> · بایت UTF-8: <b>${policy.byteLength}</b>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
201 + reply_markup: { inline_keyboard: workspaceButtons(updated) }
202 + };
203 + }
204 +
205 + let message;
206 + try {
207 + message = normalizeCommitMessage(text);
208 + } catch (error) {
209 + return {
210 + text: `⚠️ <b>پیام Commit ذخیره نشد</b>\n${escapeHtml(error?.message || 'Commit message is invalid')}\n\nاین ورودی مصرف شد؛ برای تلاش دوباره «پیام Commit» را بزنید.`,
211 + reply_markup: { inline_keyboard: [[{ text: '📝 بازگشت به Draft', callback_data: `ws:${workspace.id}` }]] }
212 + };
213 + }
214 + const digest = await digestText(message);
215 + const updated = await workspaces.setCommitMessage({ ownerId, workspaceId, message, digest });
216 + return {
217 + text: `✅ <b>پیام Commit ذخیره شد</b>\n<code>${escapeHtml(message)}</code>\n\nهنوز هیچ تغییری در GitHub انجام نشده است.`,
218 + reply_markup: { inline_keyboard: workspaceButtons(updated) }
219 + };
220 + };
221 +
222 + const renderDiff = async (workspaceId, ownerId) => {
223 + const workspace = await requireWorkspace(workspaceId, ownerId);
224 + const diff = buildUnifiedDiff({
225 + path: workspace.path,
226 + before: workspace.originalText,
227 + after: workspace.draftText,
228 + maxChars: 2400
229 + });
230 + const truncation = diff.truncated ? '\n⚠️ نمایش Diff کوتاه شده؛ شمارش‌ها بر اساس محتوای کامل هستند.' : '';
231 + return {
232 + text: `🔍 <b>Diff محلی</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\n+${diff.additions} / -${diff.deletions}${truncation}\n➖➖➖➖➖➖➖➖➖➖\n<pre>${escapeHtml(diff.text)}</pre>`,
233 + reply_markup: { inline_keyboard: [[{ text: '📝 Draft', callback_data: `ws:${workspace.id}` }, { text: '✅ آماده Commit', callback_data: `wready:${workspace.id}` }]] }
234 + };
235 + };
236 +
237 + const sealReadyIntent = async (workspaceId, ownerId) => {
238 + const workspace = await requireWorkspace(workspaceId, ownerId);
239 + if (workspace.draftText === workspace.originalText) throw new Error('No draft change to commit');
240 + const commitMessage = normalizeCommitMessage(workspace.commitMessage);
241 + const contentDigest = await digestText(workspace.draftText);
242 + const commitMessageDigest = await digestText(commitMessage);
243 + const targetBranch = makeTargetBranch(workspace.id);
244 + const createdAt = Number(workspace.createdAt);
245 + const commitTimestamp = new Date(Number.isFinite(createdAt) ? createdAt : 0).toISOString();
246 + const material = {
247 + repoId: Number(workspace.repoId),
248 + workspaceId: workspace.id,
249 + baseBranch: workspace.baseBranch,
250 + baseHeadSha: workspace.baseHeadSha,
251 + baseTreeSha: workspace.baseTreeSha,
252 + path: workspace.path,
253 + sourceBlobSha: workspace.blobSha,
254 + contentDigest,
255 + commitMessageDigest,
256 + targetBranch,
257 + commitTimestamp
258 + };
259 + const intentDigest = await digestText(JSON.stringify(material));
260 + const intent = await workspaces.sealIntent({
261 + ownerId,
262 + workspaceId,
263 + intent: { ...material, intentDigest }
264 + });
265 + if (!intent?.id || !/^[A-Za-z0-9_-]{8}$/.test(intent.id)) throw new Error('Commit intent ID is invalid');
266 + return {
267 + text: `✅ <b>آمادهٔ تأیید Commit</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nBranch: <code>${escapeHtml(targetBranch)}</code>\nBase: <code>${escapeHtml(String(workspace.baseHeadSha).slice(0, 10))}</code>\n\nمرحلهٔ بعد فقط درخواست تأیید امن را می‌سازد؛ تا تأیید معتبر مصرف نشود GitHub WRITE اجرا نمی‌شود.`,
268 + reply_markup: {
269 + inline_keyboard: [
270 + [{ text: '✅ تأیید و Commit', callback_data: `wscommit:${workspace.repoId}:${intent.id}` }],
271 + [{ text: '🔍 Diff', callback_data: `wdiff:${workspace.id}` }, { text: '📝 Draft', callback_data: `ws:${workspace.id}` }]
272 + ]
273 + }
274 + };
275 + };
276 +
277 + const cancelDraft = async (workspaceId, ownerId) => {
278 + const workspace = await requireWorkspace(workspaceId, ownerId);
279 + await workspaces.cancelWorkspace({ ownerId, workspaceId });
280 + return {
281 + text: `🗑 <b>Draft لغو شد</b>\nفایل: <code>${escapeHtml(workspace.path)}</code>\nهیچ تغییری در GitHub انجام نشد.`,
282 reply_markup: { inline_keyboard: [[{ text: '🔙 فایل‌ها', callback_data: `files:${workspace.repoId}` }]] }
283 };
284 };
@@ -132,6 +294,10 @@ export function createWorkspaceController({ github, workspaces } = {}) {
294 if (parsed.kind === 'root') return renderDirectory(parsed.repoId, '', ownerId);
295 if (parsed.kind === 'workspace') return renderWorkspace(parsed.workspaceId, ownerId);
296 if (parsed.kind === 'edit') return createDraft(parsed.refId, ownerId);
297 + if (parsed.kind === 'input') return prepareInput(parsed.workspaceId, parsed.mode, ownerId);
298 + if (parsed.kind === 'diff') return renderDiff(parsed.workspaceId, ownerId);
299 + if (parsed.kind === 'ready') return sealReadyIntent(parsed.workspaceId, ownerId);
300 + if (parsed.kind === 'cancel') return cancelDraft(parsed.workspaceId, ownerId);
301 const ref = await workspaces.resolveNavigationRef({ ownerId, refId: parsed.refId });
302 if (!ref) throw new Error('Workspace navigation reference is missing or expired');
303 return ref.type === 'dir'
@@ -139,6 +305,16 @@ export function createWorkspaceController({ github, workspaces } = {}) {
305 : renderFile(parsed.refId, ownerId);
306 }
307 };
308 + },
309 +
310 + resolveMessage(payload, context = {}) {
311 + const pending = payload?.pending;
312 + if (!pending || !['draft', 'commit_message'].includes(String(pending.mode || ''))) return null;
313 + if (!new RegExp(`^${HANDLE_10}$`).test(String(pending.workspaceId || ''))) return null;
314 + return {
315 + actionId: 'github.workspace.input.apply',
316 + execute: async () => applyPendingInput({ pending, text: String(payload?.text ?? '') }, ownerFrom(context))
317 + };
318 }
319 };
320 }