Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd637d0141 | ||
|
|
785fb990b4 | ||
|
|
f8c2c080f9 | ||
|
|
47220929bf | ||
|
|
3b4bb618dd | ||
|
|
9adfcd01b6 | ||
|
|
64e764b996 | ||
|
|
76eed47487 | ||
|
|
05b2f769e4 | ||
|
|
40b124bc2c | ||
|
|
4ab0ffde58 | ||
|
|
ab77beb3fe | ||
|
|
170828b308 | ||
|
|
08139bc3ee | ||
|
|
4589c46f16 | ||
|
|
6b924a4757 | ||
|
|
1602528e47 | ||
|
|
d28140bbd1 | ||
|
|
3f559a50ea | ||
|
|
e7a4eb3331 | ||
|
|
7b27f85b39 | ||
|
|
7204a426af | ||
|
|
2aad1a9bef | ||
|
|
dbadc73a57 | ||
|
|
59bc13c5b0 | ||
|
|
5c370cbe33 | ||
|
|
475739328c | ||
|
|
411e40d117 | ||
|
|
88e5f3f33b |
No files matched your search
@@ -115,7 +115,12 @@ explicit **Add blocked item anyway** override, while an unavailable dependency l
|
||||
as unknown rather than unblocked. Starting a Today work session also
|
||||
stores an account-bound checkpoint on the current device and starts an account-bound actual-time timer for the exact item. The sticky mobile session controls show elapsed time beside the estimate and let the operator pause or resume it. Switching items preserves each item's elapsed value, while wall-clock checkpoints keep a running timer accurate through app backgrounding, reloads, and installed-app restarts without double counting. **End session** stops accumulation but retains measured time with the private device data. The recap identifies each item by title and repository, reports per-item estimate variance, and **Save recap & adjust plan** continues into the current ordered Today plan without changing Gitea time entries. Eligible non-zero rows also offer an unchecked **Log Xm to Gitea** control. **Log selected time to Gitea** saves the recap and sends only those corrected durations to each canonical issue or pull request; confirmed account-scoped receipts prevent a completed row from being posted again, while definite failures retain the draft for an explicit retry. If the upstream response is lost after sending, Stackchain marks the row for verification in Gitea instead of risking an automatic duplicate. Actual time appears in planning as an explicit estimate recommendation; it changes only the planning draft until the operator chooses **Save plan** or **Save & start**. After the recap is confirmed, this recommendation handoff remains account-bound on the device through reloads, app restarts, planner cancellation, and failed plan admission. Opening **Plan Today** resumes it without reposting the recap; a successful plan save clears it, while **Discard recap feedback** removes only the handoff and leaves recap history unchanged. The recap and any corrected actual minutes are also saved as an account-bound device draft: an offline save failure can survive a reload and retry with the same idempotent session ID, while another account cannot view it. The draft and timer are cleared only after the account confirms the recap.
|
||||
After a reload or installed-app
|
||||
restart, **Resume Today** reopens the saved item (or the next surviving item if work changed);
|
||||
restart, **Resume Today** reopens the saved item (or the next surviving item if work changed). In an open
|
||||
assigned issue, the mobile detail sheet renders Markdown checklist items as touch-safe controls and keeps
|
||||
**Add step** directly beside the plan. A new step is normalized, checked for duplicates, and appended without
|
||||
exposing or replacing the full issue description. Offline additions enter the same account-bound durable
|
||||
issue-content queue as checklist toggles; reconnect conflict review applies unique local additions to the
|
||||
latest remote body while preserving remote prose and task-state changes.
|
||||
**Comment & next** on that current issue or pull request posts the handoff online or admits it
|
||||
to durable account-bound delivery, then removes the item only from Today and opens the next
|
||||
one without closing or merging it. **Reply & next** provides the same one-action continuation
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync, getOwnerLogin = () => '', createOperationId, now = () => Date.now(), maxItems = 50 }) {
|
||||
function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync, getOwnerLogin = () => '', createOperationId, mergeChecklistConflict, now = () => Date.now(), maxItems = 50 }) {
|
||||
const storageKey = 'stackchain.authored-outbox.v1';
|
||||
const makeId = createOperationId || (() =>
|
||||
globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random().toString(16).slice(2)
|
||||
);
|
||||
const pending = new Map();
|
||||
const supportedKinds = new Set(['issue-comment', 'pull-comment', 'update-reply', 'update-reply-read', 'pull-review', 'issue-close', 'issue-blocker']);
|
||||
const supportedKinds = new Set(['issue-comment', 'pull-comment', 'update-reply', 'update-reply-read', 'pull-review', 'issue-close', 'issue-blocker', 'issue-content']);
|
||||
|
||||
function checklistOperation(value) {
|
||||
const action = String(value?.action || '');
|
||||
if (!['rename', 'remove', 'move-earlier', 'move-later'].includes(action)) return null;
|
||||
return {
|
||||
action,
|
||||
index:Number(value.index),
|
||||
...(action === 'rename' ? { label:String(value.label || '') } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function reviewFingerprint(message) {
|
||||
return JSON.stringify({
|
||||
@@ -61,6 +71,23 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
throw new Error('A review for this saved head is already queued. Open Drafts to inspect or discard it first.');
|
||||
}
|
||||
}
|
||||
if (message.kind === 'issue-content') {
|
||||
const queuedContent = items.find(item => item.kind === 'issue-content' && item.status === 'queued' &&
|
||||
item.ownerLogin === ownerLogin && item.repository === String(message.repository || '') &&
|
||||
item.number === Number(message.number || 0));
|
||||
if (queuedContent) {
|
||||
const operation = checklistOperation(message.checklistOperation);
|
||||
const replacement = {
|
||||
...queuedContent,
|
||||
operationId: String(requestedOperationId || makeId()).slice(0, 128),
|
||||
title: String(message.title || ''),
|
||||
body: String(message.body || ''),
|
||||
...(operation ? { checklistOperations:[...(queuedContent.checklistOperations || []), operation] } : {}),
|
||||
};
|
||||
write(items.map(item => item.id === queuedContent.id ? replacement : item), mirror);
|
||||
return replacement;
|
||||
}
|
||||
}
|
||||
if (items.length >= maxItems) throw new Error('Message outbox is full. Send or discard a queued message first.');
|
||||
const id = String(requestedOperationId || makeId()).slice(0, 128);
|
||||
const item = {
|
||||
@@ -96,6 +123,14 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
blockerNumber: Number(message.blockerNumber || 0),
|
||||
present: message.present === true,
|
||||
} : {}),
|
||||
...(message.kind === 'issue-content' ? {
|
||||
title: String(message.title || ''),
|
||||
baseBody: String(message.baseBody ?? message.body ?? ''),
|
||||
expectedUpdatedAt: String(message.expectedUpdatedAt || ''),
|
||||
...(checklistOperation(message.checklistOperation) ? {
|
||||
checklistOperations:[checklistOperation(message.checklistOperation)],
|
||||
} : {}),
|
||||
} : {}),
|
||||
};
|
||||
items.push(item);
|
||||
write(items, mirror);
|
||||
@@ -103,6 +138,7 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
}
|
||||
|
||||
async function enqueueDurably(message) {
|
||||
const previousItems = read();
|
||||
const item = enqueue(message, false);
|
||||
if (message.attachment && ['update-reply', 'update-reply-read'].includes(message.kind) &&
|
||||
(!backgroundSync?.reconcile || !backgroundSync?.requestSync)) {
|
||||
@@ -124,7 +160,7 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
try {
|
||||
await backgroundSync.reconcile(durableItems, 'authored');
|
||||
} catch (error) {
|
||||
write(read().filter(candidate => candidate.id !== item.id), false);
|
||||
write(previousItems, false);
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
@@ -171,6 +207,9 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
if (item.kind === 'issue-blocker') {
|
||||
return 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(item.number) + '/blockers';
|
||||
}
|
||||
if (item.kind === 'issue-content') {
|
||||
return 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(item.number) + '/content';
|
||||
}
|
||||
if (item.kind === 'pull-review') {
|
||||
return 'api/v1/repos/' + repository + '/pulls/' + encodeURIComponent(item.number) + '/review';
|
||||
}
|
||||
@@ -246,9 +285,11 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
decision: item.decision,
|
||||
expected_head_sha: item.expectedHeadSha,
|
||||
comments: item.comments,
|
||||
} : item.kind === 'issue-content' ? {
|
||||
title:item.title, body:item.body, expected_updated_at:item.expectedUpdatedAt,
|
||||
} : { body: item.body };
|
||||
result = await fetchJson(endpoint(item), {
|
||||
method: 'POST',
|
||||
method: item.kind === 'issue-content' ? 'PATCH' : 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
@@ -256,6 +297,10 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (item.kind === 'issue-content' &&
|
||||
(result?.number !== item.number || result?.title !== item.title || result?.body !== item.body)) {
|
||||
throw new Error('Checklist update was not confirmed.');
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!result) return { blocked: true };
|
||||
@@ -334,6 +379,51 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
return retryItem(id, currentLogin);
|
||||
}
|
||||
|
||||
async function resolveIssueContentConflict(id, latest, currentLogin) {
|
||||
const previousItems = read();
|
||||
const item = previousItems.find(candidate => candidate.id === id);
|
||||
currentLogin = String(currentLogin || '').trim();
|
||||
if (!item || item.kind !== 'issue-content' || item.status !== 'attention') {
|
||||
throw new Error('This checklist conflict is no longer available.');
|
||||
}
|
||||
if (!currentLogin || item.ownerLogin !== currentLogin) {
|
||||
throw new Error('Confirm the account that queued this checklist update.');
|
||||
}
|
||||
if (typeof mergeChecklistConflict !== 'function') {
|
||||
throw new Error('Checklist conflict review is unavailable.');
|
||||
}
|
||||
const merged = mergeChecklistConflict({
|
||||
baseBody: String(item.baseBody ?? item.body ?? ''),
|
||||
localBody: String(item.body || ''),
|
||||
remoteBody: String(latest?.body || ''),
|
||||
});
|
||||
if (merged.conflicts?.length) return merged;
|
||||
if (!String(latest?.updated_at || '')) throw new Error('Latest issue revision is unavailable.');
|
||||
const rebased = {
|
||||
...item,
|
||||
operationId: String(makeId()).slice(0, 128),
|
||||
title: String(latest?.title || ''),
|
||||
baseBody: String(latest?.body || ''),
|
||||
body: merged.body,
|
||||
expectedUpdatedAt: String(latest.updated_at),
|
||||
status: 'queued',
|
||||
};
|
||||
delete rebased.error;
|
||||
delete rebased.deliveryState;
|
||||
const nextItems = previousItems.map(candidate => candidate.id === id ? rebased : candidate);
|
||||
write(nextItems, false);
|
||||
if (backgroundSync?.reconcile) {
|
||||
try { await backgroundSync.reconcile(nextItems, 'authored'); }
|
||||
catch (error) {
|
||||
write(previousItems, false);
|
||||
throw error;
|
||||
}
|
||||
try { await backgroundSync.requestSync?.(); }
|
||||
catch (_error) { /* Foreground retry remains available. */ }
|
||||
}
|
||||
return { ...merged, item: rebased };
|
||||
}
|
||||
|
||||
function reconcileBackground(records) {
|
||||
const statuses = new Map((records || []).map(item => [item.id, item]));
|
||||
const items = read().flatMap(item => {
|
||||
@@ -359,7 +449,8 @@ function createAuthoredOutbox({ storage, fetchJson, coordinator, backgroundSync,
|
||||
return items;
|
||||
}
|
||||
|
||||
return { enqueue, enqueueDurably, update, discard, flush, retry, reconcileBackground, list: () => read().map(item => ({ ...item })) };
|
||||
return { enqueue, enqueueDurably, update, discard, flush, retry, resolveIssueContentConflict,
|
||||
reconcileBackground, list: () => read().map(item => ({ ...item })) };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createAuthoredOutbox;
|
||||
@@ -105,6 +105,11 @@ function createIssueSyncStore({
|
||||
};
|
||||
incoming.set(current.id, replacement);
|
||||
}
|
||||
if (current.kind === 'issue-content' && replacement.kind === 'issue-content' &&
|
||||
current.operationId !== replacement.operationId && current.status === 'sending' &&
|
||||
Number(current.claimUntil) > Number(now())) {
|
||||
throw new Error('Checklist sync is already delivering. Retry this change.');
|
||||
}
|
||||
if ((current.status === 'sending' && Number(current.claimUntil) > Number(now())) ||
|
||||
(['attention', 'authorization'].includes(current.status) &&
|
||||
replacement.status === current.status) ||
|
||||
@@ -410,6 +415,24 @@ function createBackgroundIssueSync({
|
||||
},
|
||||
};
|
||||
}
|
||||
if (item.kind === 'issue-content') {
|
||||
return {
|
||||
url: base + 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(item.number) + '/content',
|
||||
options: {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
'Idempotency-Key': item.operationId,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
title: item.title,
|
||||
body: item.body,
|
||||
expected_updated_at: item.expectedUpdatedAt,
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (item.kind === 'pull-review') {
|
||||
return {
|
||||
url: base + 'api/v1/repos/' + repository + '/pulls/' + encodeURIComponent(item.number) + '/review',
|
||||
@@ -706,6 +729,12 @@ function createBackgroundIssueSync({
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
if (item.kind === 'issue-content' &&
|
||||
(delivered?.number !== item.number || delivered?.title !== item.title || delivered?.body !== item.body)) {
|
||||
const error = new Error('Checklist update was not confirmed.');
|
||||
error.status = 422;
|
||||
throw error;
|
||||
}
|
||||
await completeClaim(item, delivered);
|
||||
const receipt = receiptFor(item, 'confirmed', delivered);
|
||||
return item.kind ? { message: delivered, receipt } : { issue: delivered, receipt };
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
function mergeChecklistConflict({ baseBody, localBody, remoteBody, operations = [] }) {
|
||||
const taskPattern = /^(\s*[-*+]\s+\[)([ xX])(\]\s+)(.*)$/;
|
||||
|
||||
function tasks(body) {
|
||||
const entries = [];
|
||||
String(body || '').split('\n').forEach((line, lineIndex) => {
|
||||
const match = line.match(taskPattern);
|
||||
if (!match) return;
|
||||
const label = match[4].trim();
|
||||
const key = label.replace(/\s+/g, ' ').toLocaleLowerCase();
|
||||
if (!key) return;
|
||||
entries.push({ key, label, checked: match[2].toLowerCase() === 'x', lineIndex, match });
|
||||
});
|
||||
return entries;
|
||||
}
|
||||
|
||||
function grouped(entries) {
|
||||
const result = new Map();
|
||||
entries.forEach(entry => result.set(entry.key, [...(result.get(entry.key) || []), entry]));
|
||||
return result;
|
||||
}
|
||||
|
||||
function replayOperations(body, requested, reportChanges) {
|
||||
let lines = String(body || '').split('\n');
|
||||
const visibleTasks = value => tasks(value).filter(entry => /^[-*+]/.test(entry.match[1]));
|
||||
const logical = visibleTasks(baseBody).map(entry => ({ key:entry.key, label:entry.label }));
|
||||
const replayed = [];
|
||||
for (const operation of requested) {
|
||||
const index = Number(operation?.index);
|
||||
const target = logical[index];
|
||||
if (!target) return { body:null, changes:replayed, conflict:{ label:'Checklist step', reason:'missing' } };
|
||||
let entries = visibleTasks(lines.join('\n'));
|
||||
const matches = entries.filter(entry => entry.key === target.key);
|
||||
if (matches.length !== 1) {
|
||||
return { body:null, changes:replayed, conflict:{
|
||||
label:target.label, reason:matches.length ? 'ambiguous' : 'missing',
|
||||
} };
|
||||
}
|
||||
const match = matches[0];
|
||||
if (operation.action === 'rename') {
|
||||
const label = String(operation.label || '').trim().replace(/\s+/g, ' ');
|
||||
const key = label.toLocaleLowerCase();
|
||||
if (!label || entries.some(entry => entry.key === key && entry.lineIndex !== match.lineIndex)) {
|
||||
return { body:null, changes:replayed, conflict:{ label:target.label, reason:'ambiguous' } };
|
||||
}
|
||||
lines[match.lineIndex] = match.match[1] + match.match[2] + match.match[3] + label;
|
||||
if (reportChanges) replayed.push({ label:target.label, renamed:label });
|
||||
target.label = label;
|
||||
target.key = key;
|
||||
} else if (operation.action === 'remove') {
|
||||
lines.splice(match.lineIndex, 1);
|
||||
logical.splice(index, 1);
|
||||
if (reportChanges) replayed.push({ label:target.label, removed:true });
|
||||
} else if (operation.action === 'move-earlier' || operation.action === 'move-later') {
|
||||
const neighborIndex = operation.action === 'move-earlier' ? index - 1 : index + 1;
|
||||
const neighbor = logical[neighborIndex];
|
||||
const neighborMatches = neighbor ? entries.filter(entry => entry.key === neighbor.key) : [];
|
||||
if (neighborMatches.length !== 1 || Math.abs(neighborMatches[0].lineIndex - match.lineIndex) !== 1) {
|
||||
return { body:null, changes:replayed, conflict:{ label:target.label, reason:'order-changed' } };
|
||||
}
|
||||
const neighborLine = neighborMatches[0].lineIndex;
|
||||
[lines[match.lineIndex], lines[neighborLine]] = [lines[neighborLine], lines[match.lineIndex]];
|
||||
[logical[index], logical[neighborIndex]] = [logical[neighborIndex], logical[index]];
|
||||
if (reportChanges) replayed.push({
|
||||
label:target.label, moved:operation.action === 'move-earlier' ? 'earlier' : 'later',
|
||||
});
|
||||
}
|
||||
}
|
||||
return { body:lines.join('\n'), changes:replayed, conflict:null };
|
||||
}
|
||||
|
||||
if (Array.isArray(operations) && operations.length) {
|
||||
const baseReplay = replayOperations(baseBody, operations, false);
|
||||
const remoteReplay = replayOperations(remoteBody, operations, true);
|
||||
const conflict = baseReplay.conflict || remoteReplay.conflict;
|
||||
if (conflict) return { body:null, changes:remoteReplay.changes || [], conflicts:[conflict] };
|
||||
const residual = mergeChecklistConflict({
|
||||
baseBody:baseReplay.body, localBody, remoteBody:remoteReplay.body,
|
||||
});
|
||||
return {
|
||||
body:residual.body,
|
||||
changes:[...remoteReplay.changes, ...residual.changes],
|
||||
conflicts:residual.conflicts,
|
||||
};
|
||||
}
|
||||
|
||||
const base = grouped(tasks(baseBody));
|
||||
const local = grouped(tasks(localBody));
|
||||
const remoteEntries = tasks(remoteBody);
|
||||
const remote = grouped(remoteEntries);
|
||||
const changes = [];
|
||||
const conflicts = [];
|
||||
|
||||
for (const [key, baseMatches] of base) {
|
||||
const localMatches = local.get(key) || [];
|
||||
if (baseMatches.length !== 1 || localMatches.length !== 1) continue;
|
||||
if (baseMatches[0].checked === localMatches[0].checked) continue;
|
||||
const remoteMatches = remote.get(key) || [];
|
||||
if (remoteMatches.length !== 1) {
|
||||
conflicts.push({
|
||||
label: baseMatches[0].label,
|
||||
reason: remoteMatches.length ? 'ambiguous' : 'missing',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
changes.push({ label: remoteMatches[0].label, checked: localMatches[0].checked });
|
||||
}
|
||||
|
||||
for (const [key, localMatches] of local) {
|
||||
if (base.has(key)) continue;
|
||||
if (localMatches.length !== 1) {
|
||||
conflicts.push({ label:localMatches[0].label, reason:'ambiguous' });
|
||||
continue;
|
||||
}
|
||||
const remoteMatches = remote.get(key) || [];
|
||||
if (remoteMatches.length > 1) {
|
||||
conflicts.push({ label: localMatches[0].label, reason: 'ambiguous' });
|
||||
continue;
|
||||
}
|
||||
if (remoteMatches.length === 0) {
|
||||
changes.push({ label: localMatches[0].label, checked:localMatches[0].checked, added:true });
|
||||
}
|
||||
}
|
||||
|
||||
if (conflicts.length) return { body: null, changes, conflicts };
|
||||
const desired = new Map(changes.map(change => [
|
||||
change.label.replace(/\s+/g, ' ').toLocaleLowerCase(), change.checked,
|
||||
]));
|
||||
const lines = String(remoteBody || '').split('\n');
|
||||
remoteEntries.forEach(entry => {
|
||||
if (!desired.has(entry.key)) return;
|
||||
const marker = desired.get(entry.key) ? 'x' : ' ';
|
||||
lines[entry.lineIndex] = entry.match[1] + marker + entry.match[3] + entry.match[4];
|
||||
});
|
||||
changes.filter(change => change.added).forEach(change => {
|
||||
lines.push('- [' + (change.checked ? 'x' : ' ') + '] ' + change.label);
|
||||
});
|
||||
return { body: lines.join('\n'), changes, conflicts: [] };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined') module.exports = mergeChecklistConflict;
|
||||
@@ -43,6 +43,85 @@ function buildRelatedDraft(value = {}, template = null) {
|
||||
return draft;
|
||||
}
|
||||
|
||||
function relatedChecklistDraft(item, label) {
|
||||
const title = String(label || '').trim().replace(/\s+/g, ' ').slice(0, 240);
|
||||
if (!title) throw new Error('Choose a checklist step to file.');
|
||||
const repository = String(item?.repository || '');
|
||||
const number = Number(item?.number);
|
||||
const url = String(item?.url || '');
|
||||
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) ||
|
||||
!Number.isInteger(number) || number < 1 || !/^https:\/\//.test(url)) {
|
||||
throw new Error('The parent issue link is unavailable.');
|
||||
}
|
||||
return {repository, title,
|
||||
body:'Related to [' + repository + '#' + number + '](' + url + ').', labelIds:[]};
|
||||
}
|
||||
|
||||
function linkChecklistTask(raw, targetIndex, child) {
|
||||
const url = String(child?.url || '');
|
||||
if (!/^https:\/\//.test(url)) throw new Error('The related issue link is unavailable.');
|
||||
const parts = String(raw || '').split(/(\r\n|\n|\r)/);
|
||||
let fenced = false;
|
||||
let taskIndex = 0;
|
||||
for (let index = 0; index < parts.length; index += 2) {
|
||||
const line = parts[index];
|
||||
if (/^\s*```/.test(line)) { fenced = !fenced; continue; }
|
||||
if (fenced) continue;
|
||||
const task = line.match(/^(\s*[-*+]\s+\[[ xX]\]\s+)(.*)$/);
|
||||
if (!task) continue;
|
||||
if (taskIndex === Number(targetIndex)) {
|
||||
if (/^\s*\[[^\]]+\]\([^)]+\)\s*$/.test(task[2])) throw new Error('That checklist step is already linked.');
|
||||
const label = task[2].trim().replace(/\s+/g, ' ');
|
||||
parts[index] = task[1] + '[' + label + '](' + url + ')';
|
||||
return parts.join('');
|
||||
}
|
||||
taskIndex += 1;
|
||||
}
|
||||
throw new Error('The checklist step is no longer available.');
|
||||
}
|
||||
|
||||
function createChecklistPromotion({ issueController, issueCapture, clearAttachments, onLinked, onStatus }) {
|
||||
let pending = null;
|
||||
const persistedPromotion = value => ({
|
||||
item:{repository:value.repository, number:value.number, url:value.url},
|
||||
detail:{title:value.title, body:value.body, updated_at:value.updatedAt}, taskIndex:value.taskIndex,
|
||||
});
|
||||
return {
|
||||
pending:() => Boolean(pending),
|
||||
start(context) {
|
||||
pending = {item:{...context.item}, detail:{...context.detail}, taskIndex:Number(context.taskIndex)};
|
||||
const draft = issueController.relatedTaskDraft(context.item, context.detail, context.taskIndex, context.label);
|
||||
issueCapture.saveDraft(draft);
|
||||
clearAttachments();
|
||||
return draft;
|
||||
},
|
||||
cancel() { if (!pending) return false; pending = null; issueCapture.clearDraft(); return true; },
|
||||
deliveryContext() {
|
||||
if (!pending) return null;
|
||||
return {repository:pending.item.repository, number:pending.item.number, url:pending.item.url,
|
||||
title:pending.detail.title, body:pending.detail.body, updatedAt:pending.detail.updated_at,
|
||||
taskIndex:pending.taskIndex};
|
||||
},
|
||||
async finish(child, persisted = null) {
|
||||
const promotion = pending || (persisted ? persistedPromotion(persisted) : null);
|
||||
if (!promotion || !child) return false;
|
||||
pending = null;
|
||||
try {
|
||||
const confirmed = await issueController.linkRelatedTask(
|
||||
promotion.item, promotion.detail, promotion.taskIndex, child
|
||||
);
|
||||
onLinked(promotion, confirmed);
|
||||
onStatus('Related issue created and linked from its parent checklist.');
|
||||
return true;
|
||||
} catch (error) {
|
||||
onStatus('Related issue created, but the parent link needs attention.' +
|
||||
(child.url ? ' ' + child.url : '') + ' ' + error.message);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createIssueOwnerPicker(issueCapture, documentRef, onChange) {
|
||||
const NO_OWNER = '__unassigned__';
|
||||
const select = documentRef.querySelector('#create-issue-assignee');
|
||||
@@ -758,5 +837,8 @@ function createIssueCapture({ fetchJson, storage, createOperationId = newIssueOp
|
||||
createIssueCapture.normalizeSharedContent = normalizeSharedContent;
|
||||
createIssueCapture.createOwnerPicker = createIssueOwnerPicker;
|
||||
createIssueCapture.buildRelatedDraft = buildRelatedDraft;
|
||||
createIssueCapture.relatedChecklistDraft = relatedChecklistDraft;
|
||||
createIssueCapture.linkChecklistTask = linkChecklistTask;
|
||||
createIssueCapture.createChecklistPromotion = createChecklistPromotion;
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createIssueCapture;
|
||||
+32
-2
@@ -469,11 +469,33 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.issue-sheet-panel { width:min(560px,100%); height:100%; overflow:auto; padding:18px; background:#0b1526; border-left:1px solid #2a496e; }
|
||||
.issue-sheet-header { display:flex; align-items:center; justify-content:space-between; gap:10px; }
|
||||
.issue-sheet-header button { min-height:44px; }
|
||||
.completed-filed-actions { position:fixed; right:0; bottom:0; z-index:57; box-sizing:border-box; width:min(560px,100%); display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:10px; margin:0; padding:10px 12px calc(10px + env(safe-area-inset-bottom)); border:1px solid #4ade80; border-radius:12px 0 0; background:rgba(11,21,38,.98); overflow-wrap:anywhere; }
|
||||
.completed-filed-actions { position:fixed; right:0; bottom:0; z-index:57; box-sizing:border-box; width:min(560px,100%); display:grid; grid-template-columns:minmax(0,1fr); align-items:center; gap:8px; margin:0; padding:10px 12px calc(10px + env(safe-area-inset-bottom)); border:1px solid #4ade80; border-radius:12px 0 0; background:rgba(11,21,38,.98); overflow-wrap:anywhere; }
|
||||
.completed-filed-actions[hidden] { display:none; }
|
||||
.completed-filed-actions button { min-height:44px; min-width:0; }
|
||||
#issue-sheet:has(.completed-filed-actions:not([hidden])) .issue-sheet-panel { padding-bottom:calc(110px + env(safe-area-inset-bottom)); }
|
||||
.completed-filed-buttons { display:flex; flex-wrap:wrap; gap:8px; }
|
||||
.completed-filed-buttons button { flex:1 1 180px; }
|
||||
#issue-sheet:has(.completed-filed-actions:not([hidden])) .issue-sheet-panel { padding-bottom:calc(170px + env(safe-area-inset-bottom)); }
|
||||
.issue-sheet-content { overflow-wrap:anywhere; white-space:pre-wrap; }
|
||||
.checklist-step-editor { display:grid; gap:8px; margin:10px 0 16px; padding:12px; border:1px solid #31577f; border-radius:12px; background:#0b1526; }
|
||||
.checklist-step-editor[hidden] { display:none; }
|
||||
.checklist-step-editor input { width:100%; min-width:0; box-sizing:border-box; }
|
||||
.checklist-step-editor-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
|
||||
.checklist-step-editor button, .checklist-step-editor input { min-height:44px; }
|
||||
#remove-checklist-step { border-color:#b45309; }
|
||||
#issue-sheet.read-only .checklist-step-editor { display:none; }
|
||||
.checklist-add { display:grid; gap:8px; margin:10px 0 16px; }
|
||||
.checklist-add form { display:grid; grid-template-columns:minmax(0,1fr) auto auto; gap:8px; }
|
||||
.checklist-add form[hidden] { display:none; }
|
||||
.checklist-add input { min-width:0; width:100%; box-sizing:border-box; }
|
||||
.checklist-add button, .checklist-add input { min-height:44px; }
|
||||
#issue-sheet.read-only .checklist-add { display:none; }
|
||||
@media(max-width:340px) { .checklist-add form { grid-template-columns:1fr 1fr; } .checklist-add input { grid-column:1 / -1; } }
|
||||
.checklist-completion { position:fixed; right:0; bottom:0; z-index:58; box-sizing:border-box; width:min(560px,100%); display:grid; grid-template-columns:minmax(0,1fr) repeat(2,minmax(0,auto)); align-items:center; gap:8px; padding:10px 12px calc(10px + env(safe-area-inset-bottom)); border-top:1px solid #4ade80; background:rgba(11,21,38,.98); overflow-wrap:anywhere; }
|
||||
.checklist-completion[hidden] { display:none; }
|
||||
.checklist-completion button { min-height:44px; min-width:0; }
|
||||
#issue-sheet:has(.checklist-completion:not([hidden])) .issue-sheet-panel { padding-bottom:calc(118px + env(safe-area-inset-bottom)); }
|
||||
#issue-sheet:has(.checklist-completion:not([hidden])) .work-session-nav { display:none; }
|
||||
@media(max-width:420px) { .checklist-completion { grid-template-columns:1fr 1fr; } .checklist-completion span { grid-column:1 / -1; } }
|
||||
.issue-blockers { max-width:100%; overflow-x:hidden; margin:16px 0; padding:12px; border:1px solid #b45309; border-radius:12px; background:#291b0c; }
|
||||
.issue-blockers h2 { margin-top:0; }
|
||||
.issue-blocker-list { display:grid; gap:8px; }
|
||||
@@ -640,7 +662,9 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.markdown-content .task-list-item { display:flex; gap:8px; align-items:flex-start; }
|
||||
.markdown-content .task-list-item input { flex:0 0 auto; margin-top:3px; }
|
||||
.markdown-content .task-list-toggle { min-width:44px; min-height:44px; margin:-9px 0 -9px -9px; cursor:pointer; accent-color:#60a5fa; }
|
||||
.markdown-content .task-list-manage { min-width:44px; min-height:44px; margin:-9px -9px -9px auto; padding:6px 8px; flex:0 0 auto; }
|
||||
.markdown-content.checklist-pending .task-list-toggle { opacity:.65; cursor:wait; }
|
||||
.markdown-content.checklist-pending .task-list-manage { opacity:.65; cursor:wait; }
|
||||
.markdown-content a { min-height:44px; display:inline-flex; align-items:center; max-width:100%; overflow-wrap:anywhere; }
|
||||
@media(max-width:320px) { .find-work-panel { padding:12px; overflow-x:hidden; } .find-work-card { min-width:0; } .my-work-actions { width:100%; } .my-work-actions button { flex:1 1 100%; } }
|
||||
.create-issue-sheet { position:fixed; inset:0; z-index:57; display:none; justify-content:flex-end; background:rgba(5,12,21,.72); backdrop-filter:blur(4px); }
|
||||
@@ -649,6 +673,12 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.create-issue-header { display:flex; align-items:center; justify-content:space-between; gap:10px; }
|
||||
.create-issue-header button, .create-issue-actions button, .create-issue-capture-actions button { min-height:44px; }
|
||||
.create-issue-form { display:grid; gap:12px; }
|
||||
.voice-issue-capture { display:grid; gap:8px; min-width:0; padding:12px; border:1px solid #31577f; border-radius:12px; background:#101d31; }
|
||||
.voice-issue-capture[hidden], .voice-issue-review[hidden], .voice-issue-controls button[hidden] { display:none; }
|
||||
.voice-issue-heading, .voice-issue-review { display:grid; gap:6px; }
|
||||
.voice-issue-controls, .voice-issue-review-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
|
||||
.voice-issue-controls button, .voice-issue-review-actions button { min-width:0; min-height:44px; }
|
||||
#voice-issue-transcript { box-sizing:border-box; width:100%; min-height:96px; resize:vertical; }
|
||||
.create-issue-capture-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; padding:10px 0; padding-bottom:calc(10px + env(safe-area-inset-bottom)); background:#0b1526; }
|
||||
.create-issue-capture-actions[hidden] { display:none; }
|
||||
.create-issue-filing { display:grid; gap:12px; min-width:0; }
|
||||
|
||||
+245
-14
@@ -7,6 +7,7 @@
|
||||
mediaQuery: window.matchMedia('(max-width: 600px)'),
|
||||
entries: [
|
||||
{ panel:qs('#issue-sheet .issue-sheet-panel'), workspace:qs('.issue-comment-composer'), composer:qs('#issue-comment'), submit:qs('#send-issue-comment'), status:qs('#issue-comment-status') },
|
||||
{ panel:qs('#issue-sheet .issue-sheet-panel'), workspace:qs('.checklist-add'), composer:qs('#add-checklist-step'), submit:qs('#save-checklist-step'), status:qs('#add-checklist-step-status') },
|
||||
{ panel:qs('#pull-sheet .pull-sheet-panel'), workspace:qs('.pull-comment-composer'), composer:qs('#pull-comment'), submit:qs('#send-pull-comment'), status:qs('#pull-comment-status') },
|
||||
{ panel:qs('#update-sheet .update-sheet-panel'), workspace:qs('.update-reply'), composer:qs('#update-reply'), submit:qs('#send-update-reply'), status:qs('#update-reply-status') },
|
||||
{ panel:qs('#review-sheet .review-sheet-panel'), workspace:qs('#review-inline-composer'), composer:qs('#review-inline-body'), submit:qs('#save-inline-comment'), status:qs('#review-submit-status') },
|
||||
@@ -216,6 +217,9 @@
|
||||
let selectedIssue = null;
|
||||
let selectedIssueOffline = false;
|
||||
let selectedIssueDetail = null;
|
||||
let delegatedParentReview = null;
|
||||
let dismissedChecklistBody = null;
|
||||
|
||||
let issueBlockerCandidates = [];
|
||||
let issueBlockerSearchTimer = null;
|
||||
let issueConversation = null;
|
||||
@@ -429,7 +433,11 @@
|
||||
}
|
||||
let reviewController = null;
|
||||
let wrapPreference = null;
|
||||
const issueController = createIssueSheet({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
const issueController = createIssueSheet({
|
||||
fetchJson: fetchReviewJson,
|
||||
storage: localStorage,
|
||||
enqueueDurably:message => authoredOutbox.enqueueDurably(message),
|
||||
});
|
||||
function overdueAgendaItems() {
|
||||
return agendaMyWork(activeMyWork).filter(item => item.agenda_group === 'Overdue');
|
||||
}
|
||||
@@ -599,6 +607,7 @@
|
||||
loadMilestones: item => issueController.loadMilestones(item),
|
||||
});
|
||||
let issueCapture = null;
|
||||
let checklistPromotion = null;
|
||||
let issueOwnerPicker = null;
|
||||
let issueTemplatePicker = null;
|
||||
let issueFilingMetadata = null;
|
||||
@@ -668,6 +677,7 @@
|
||||
storage: localStorage, fetchJson: fetchReviewJson, coordinator: outboxCoordinator,
|
||||
backgroundSync: backgroundIssueSync,
|
||||
getOwnerLogin: () => confirmedOwnerLogin,
|
||||
mergeChecklistConflict: mergeChecklistConflict,
|
||||
});
|
||||
const queueOfflineIssueBlocker = createOfflineIssueBlocker({
|
||||
enqueueDurably: message => authoredOutbox.enqueueDurably(message),
|
||||
@@ -725,12 +735,25 @@
|
||||
});
|
||||
let sharedLaunchState = null;
|
||||
let sharedLaunchHandled = false;
|
||||
let voiceIssueCapture = null;
|
||||
async function ensureIssueCapture() {
|
||||
return await issueCaptureFeatures.run('issue-capture', {
|
||||
trigger: qs('#new-issue'), status: qs('#my-work-action-status'),
|
||||
}, () => {
|
||||
if (!issueCapture) {
|
||||
issueCapture = createIssueCapture({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
voiceIssueCapture = createVoiceIssueCapture({
|
||||
Recognition: window.SpeechRecognition || window.webkitSpeechRecognition,
|
||||
elements: {
|
||||
root:qs('#voice-issue-capture'), start:qs('#start-voice-issue-capture'),
|
||||
stop:qs('#stop-voice-issue-capture'), review:qs('#voice-issue-review'),
|
||||
transcript:qs('#voice-issue-transcript'), append:qs('#append-voice-issue-transcript'),
|
||||
replace:qs('#replace-with-voice-issue-transcript'), discard:qs('#discard-voice-issue-transcript'),
|
||||
status:qs('#voice-issue-status'), title:qs('#create-issue-title'), body:qs('#create-issue-body'),
|
||||
},
|
||||
transcriptStore:createVoiceTranscriptStore(),
|
||||
getLogin:()=>confirmedOwnerLogin,
|
||||
});
|
||||
issueOwnerPicker = createIssueCapture.createOwnerPicker(issueCapture, document,
|
||||
() => { saveIssueCaptureDraft(); updateIssueCreateActions(); });
|
||||
issueTemplatePicker = issueCapture.bindTemplatePicker({
|
||||
@@ -753,6 +776,18 @@
|
||||
getRepository:()=>qs('#create-issue-repository').value,
|
||||
}, issueTemplatePicker);
|
||||
updateFollowUp = createUpdateFollowUp({ storage:localStorage, getLogin:()=>confirmedOwnerLogin });
|
||||
checklistPromotion = createIssueCapture.createChecklistPromotion({
|
||||
issueController, issueCapture,
|
||||
clearAttachments:()=>createIssueAttachmentController.clear(),
|
||||
onLinked:(promotion, confirmed) => {
|
||||
if (selectedIssue?.repository === promotion.item.repository &&
|
||||
selectedIssue?.number === promotion.item.number) {
|
||||
applyIssueContent(promotion.item, promotion.detail, confirmed);
|
||||
qs('#issue-sheet').classList.add('open');
|
||||
}
|
||||
},
|
||||
onStatus:message=>{ qs('#my-work-action-status').textContent = message; },
|
||||
});
|
||||
}
|
||||
if (!sharedLaunchHandled && Object.values(sharedLaunch).some(Boolean)) {
|
||||
sharedLaunchState = issueCapture.stageSharedContent(sharedLaunch);
|
||||
@@ -2740,6 +2775,7 @@
|
||||
const isUnfiled = item.kind === 'unfiled-issue';
|
||||
const reviewOutbox = item.outbox_kind === 'pull-review';
|
||||
const closureOutbox = item.outbox_kind === 'issue-close';
|
||||
const checklistConflict = item.checklist_conflict === true;
|
||||
const sendLabel = item.delivery_state === 'uncertain' ? 'Verified not posted — retry' : 'Send now';
|
||||
const outboxActions = item.quarantined ?
|
||||
'<button class="draft-copy" data-draft-index="' + index + '" type="button">Copy content</button>' +
|
||||
@@ -2759,6 +2795,9 @@
|
||||
'<button class="draft-resume" data-draft-index="' + index + '" type="button">Open current review</button>' +
|
||||
'<button class="draft-copy" data-draft-index="' + index + '" type="button">Copy feedback</button>' +
|
||||
'<button class="draft-discard" data-draft-index="' + index + '" type="button">Discard queued review</button>' :
|
||||
item.kind === 'authored-outbox' && checklistConflict ?
|
||||
'<button class="draft-review-checklist" data-draft-index="' + index + '" type="button">Review changes</button>' +
|
||||
'<button class="draft-discard" data-draft-index="' + index + '" type="button">Discard</button>' :
|
||||
item.kind === 'authored-outbox' && closureOutbox ?
|
||||
'<button class="draft-resume" data-draft-index="' + index + '" type="button">Open issue</button>' +
|
||||
'<button class="draft-authorize" data-draft-index="' + index + '" type="button">Authorize & close</button>' +
|
||||
@@ -2868,6 +2907,42 @@
|
||||
else applyOutboxResult(await issueOutbox.retry(item.outbox_id, activeFlushLogin));
|
||||
});
|
||||
});
|
||||
list.querySelectorAll('.draft-review-checklist').forEach(button => {
|
||||
button.addEventListener('click', async () => {
|
||||
const item = lastDrafts[Number(button.dataset.draftIndex)];
|
||||
const queued = authoredOutbox.list().find(candidate => candidate.id === item?.outbox_id);
|
||||
if (!item?.checklist_conflict || !queued || !activeFlushLogin) return;
|
||||
button.disabled = true;
|
||||
qs('#my-work-action-status').textContent = 'Loading the latest checklist for review…';
|
||||
try {
|
||||
const latest = await issueController.load({
|
||||
repository:item.repository, number:item.number,
|
||||
});
|
||||
const preview = mergeChecklistConflict({
|
||||
baseBody:queued.baseBody, localBody:queued.body, remoteBody:latest.body,
|
||||
});
|
||||
if (preview.conflicts.length) {
|
||||
qs('#my-work-action-status').textContent = 'Checklist changes for ' +
|
||||
preview.conflicts.map(conflict => conflict.label).join(', ') +
|
||||
' could not be matched safely. Open the issue to compare renamed or deleted tasks.';
|
||||
return;
|
||||
}
|
||||
if (!window.confirm('Apply ' + preview.changes.length + ' checklist change' +
|
||||
(preview.changes.length === 1 ? '' : 's') + ' to the latest issue? Remote prose and other tasks will stay unchanged.')) return;
|
||||
const result = await authoredOutbox.resolveIssueContentConflict(item.outbox_id, latest, activeFlushLogin);
|
||||
if (result.conflicts.length) return;
|
||||
const delivery = await authoredOutbox.retry(item.outbox_id, activeFlushLogin);
|
||||
applyAuthoredOutboxResult(delivery);
|
||||
qs('#my-work-action-status').textContent = delivery.confirmed?.length ?
|
||||
'Checklist changes applied to the latest issue.' :
|
||||
'The issue changed again. Review the checklist conflict against the new version.';
|
||||
} catch (error) {
|
||||
qs('#my-work-action-status').textContent = String(error?.message || 'Checklist review could not be loaded. Retry when online.');
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
list.querySelectorAll('.draft-authorize').forEach(button => {
|
||||
button.addEventListener('click', async () => {
|
||||
const item = lastDrafts[Number(button.dataset.draftIndex)];
|
||||
@@ -3394,9 +3469,23 @@
|
||||
}
|
||||
}
|
||||
|
||||
function renderChecklistCompletion(detail) {
|
||||
const interactive = !issueController.readOnly(selectedIssue) && detail?.state === 'open' && detail?.updated_at;
|
||||
const completion = issueController.checklistCompletion(qs('#issue-sheet-body'), {
|
||||
interactive, today:workSession.active(), offline:selectedIssueOffline,
|
||||
dismissed:dismissedChecklistBody === detail?.body,
|
||||
});
|
||||
const bar = qs('#checklist-completion');
|
||||
bar.hidden = !completion.visible;
|
||||
qs('#checklist-completion-status').textContent = completion.status;
|
||||
qs('#complete-checklist-issue').textContent = completion.label;
|
||||
}
|
||||
|
||||
function renderIssueBody(detail) {
|
||||
issueController.renderTasks(qs('#issue-sheet-body'), detail, !selectedIssueOffline &&
|
||||
!issueController.readOnly(selectedIssue) && detail.state === 'open' && detail.updated_at);
|
||||
const interactive = !issueController.readOnly(selectedIssue) && detail.state === 'open' && detail.updated_at;
|
||||
issueController.renderTasks(qs('#issue-sheet-body'), detail, interactive);
|
||||
qs('#open-add-checklist-step').disabled = !interactive;
|
||||
renderChecklistCompletion(detail);
|
||||
}
|
||||
|
||||
function applyIssueContent(editing, detail, confirmed) {
|
||||
@@ -3423,9 +3512,11 @@
|
||||
qs('#issue-planning').inert = false;
|
||||
qs('#issue-handoff').inert = false;
|
||||
selectedIssue = item;
|
||||
dismissedChecklistBody = null;
|
||||
issueMentions.dismiss();
|
||||
selectedIssueOffline = Boolean(offlineDetail);
|
||||
selectedIssueDetail = null;
|
||||
delegatedParentReview = null;
|
||||
issueConversation = null;
|
||||
issueTrigger = trigger;
|
||||
qs('#issue-sheet').classList.add('open');
|
||||
@@ -3437,12 +3528,21 @@
|
||||
candidate.repository === item.repository && candidate.number === item.number
|
||||
);
|
||||
qs('#completed-filed-actions').hidden = !item.is_completed;
|
||||
qs('#complete-parent-and-acknowledge').hidden = true;
|
||||
qs('#complete-parent-and-acknowledge').disabled = true;
|
||||
qs('#filed-claim-actions').hidden = true;
|
||||
qs('#queue-filed-issue').disabled = true;
|
||||
qs('#start-filed-issue').disabled = true;
|
||||
qs('#completed-filed-progress').textContent = item.is_completed ?
|
||||
'Completed Filed issue ' + (completedPosition + 1) + ' of ' + completedItems.length : '';
|
||||
qs('#issue-sheet-body').textContent = '';
|
||||
checklistStepManagement.reset();
|
||||
qs('#checklist-step-label').value = '';
|
||||
qs('#open-add-checklist-step').disabled = true;
|
||||
qs('#add-checklist-step-form').hidden = true;
|
||||
qs('#add-checklist-step').value = '';
|
||||
qs('#add-checklist-step-status').textContent = '';
|
||||
qs('#checklist-completion').hidden = true;
|
||||
qs('#issue-labels').textContent = '';
|
||||
qs('#issue-assignees').textContent = '';
|
||||
qs('#issue-comments').textContent = '';
|
||||
@@ -3490,8 +3590,11 @@
|
||||
qs('#release-issue').textContent = workSession.checkpointed(item) ? 'Release & next' : 'Release assignment';
|
||||
qs('#close-issue-sheet').focus();
|
||||
try {
|
||||
const detail = offlineDetail || await issueController.load(item);
|
||||
const loadedDetail = offlineDetail || await issueController.load(item);
|
||||
if (selectedIssue !== item) return;
|
||||
const detail = issueController.pendingTask(
|
||||
item, loadedDetail, authoredOutbox.list(), confirmedOwnerLogin
|
||||
);
|
||||
selectedIssueDetail = detail;
|
||||
renderPlanIssueDependencies(detail);
|
||||
issueConversation = issueController.conversation(item, detail.conversation);
|
||||
@@ -3512,6 +3615,32 @@
|
||||
qs('#issue-sheet-status').textContent = item.is_completed ?
|
||||
'Completed Filed outcome ready · review the conversation' : readOnly ? 'Filed issue ready · follow-up enabled' :
|
||||
'Issue ready · ' + (detail.state || 'open');
|
||||
const parentReference = item.is_completed && !offlineDetail ?
|
||||
issueController.delegatedParentReference(detail) : null;
|
||||
if (parentReference) {
|
||||
try {
|
||||
const parentItem = { ...parentReference, key:parentReference.repository + '#' + parentReference.number };
|
||||
const parentDetail = await issueController.load(parentItem);
|
||||
if (selectedIssue !== item) return;
|
||||
const relationship = issueController.resolveDelegatedParent(item, detail, parentDetail);
|
||||
if (relationship && parentDetail.state === 'open' && parentDetail.updated_at) {
|
||||
delegatedParentReview = { parentItem, parentDetail, relationship };
|
||||
const button = qs('#complete-parent-and-acknowledge');
|
||||
button.hidden = false;
|
||||
button.disabled = false;
|
||||
button.textContent = relationship.checklistComplete ?
|
||||
'Complete & close parent · acknowledge' : relationship.alreadyCompleted ?
|
||||
'Parent complete · acknowledge' : 'Complete parent step & acknowledge';
|
||||
qs('#completed-filed-progress').textContent = relationship.checklistComplete ?
|
||||
'Delegated outcome completes the parent checklist. Confirm to close the parent.' :
|
||||
relationship.alreadyCompleted ? 'Parent checklist already reflects this outcome.' :
|
||||
'Delegated outcome ready · complete its parent checklist step.';
|
||||
}
|
||||
} catch (_error) {
|
||||
if (selectedIssue !== item) return;
|
||||
delegatedParentReview = null;
|
||||
}
|
||||
}
|
||||
const revisableFiling = item.is_filed && !item.is_completed && detail.state === 'open';
|
||||
qs('#edit-issue-content').textContent = revisableFiling ? 'Revise filing' : 'Edit issue';
|
||||
qs('#edit-issue-content').disabled = readOnly && !revisableFiling;
|
||||
@@ -3565,7 +3694,7 @@
|
||||
}
|
||||
window.addEventListener('popstate', closeIssueEditorFromHistory);
|
||||
|
||||
qs('#acknowledge-completed-filed').addEventListener('click', () => {
|
||||
function acknowledgeCompletedFiled() {
|
||||
if (!selectedIssue?.is_completed) return;
|
||||
if (!completedFiledReview.acknowledge(selectedIssue)) {
|
||||
qs('#issue-sheet-status').textContent = 'Could not save this acknowledgement on this device. Retry.';
|
||||
@@ -3588,6 +3717,32 @@
|
||||
window.location.hash = '#/my-work/filed';
|
||||
qs('#my-work').focus();
|
||||
}
|
||||
}
|
||||
|
||||
qs('#acknowledge-completed-filed').addEventListener('click', acknowledgeCompletedFiled);
|
||||
|
||||
qs('#complete-parent-and-acknowledge').addEventListener('click', async () => {
|
||||
if (!selectedIssue?.is_completed || !delegatedParentReview) return;
|
||||
const button = qs('#complete-parent-and-acknowledge');
|
||||
const { parentItem, parentDetail, relationship } = delegatedParentReview;
|
||||
if (relationship.checklistComplete && !window.confirm(
|
||||
'Complete the final checklist step and close ' + parentItem.key + '?'
|
||||
)) return;
|
||||
button.disabled = true;
|
||||
try {
|
||||
await issueController.finishDelegatedParentReview({
|
||||
relationship, parentItem, parentDetail, childUrl:selectedIssue.url,
|
||||
updateContent:(item, payload) => issueController.updateContent(item, payload),
|
||||
closeParent:item => issueController.close(item),
|
||||
});
|
||||
acknowledgeCompletedFiled();
|
||||
} catch (error) {
|
||||
if (!selectedIssue) return;
|
||||
button.disabled = false;
|
||||
qs('#issue-sheet-status').textContent =
|
||||
'Parent review action did not finish. Reload the parent relationship and retry. ' + error.message;
|
||||
button.focus();
|
||||
}
|
||||
});
|
||||
|
||||
function renderCheckSection(prefix, detail, offline = false) {
|
||||
@@ -4167,6 +4322,11 @@
|
||||
}
|
||||
|
||||
let suppressCreateDraftOnHistoryClose = false;
|
||||
async function startChecklistPromotion(context) {
|
||||
if (!issueCapture && !await ensureIssueCapture()) throw new Error('Issue capture is unavailable.');
|
||||
checklistPromotion.start(context);
|
||||
await openCreateIssueSheet();
|
||||
}
|
||||
const issueFilingReceipt = createIssueFilingReceipt({
|
||||
root:qs('#issue-filing-receipt'), heading:qs('#issue-filing-receipt-heading'),
|
||||
key:qs('#issue-filing-receipt-key'), title:qs('#issue-filing-receipt-title'),
|
||||
@@ -4196,6 +4356,7 @@
|
||||
return;
|
||||
}
|
||||
qs('#create-issue-sheet').classList.remove('open');
|
||||
voiceIssueCapture.cancel();
|
||||
mobileComposerViewport.close(qs('.create-issue-panel'));
|
||||
clearTimeout(duplicateCheckTimer);
|
||||
qs('#create-issue-duplicates').hidden = true;
|
||||
@@ -4233,6 +4394,9 @@
|
||||
const keys = result.confirmed.map(issue => issue.repository + '#' + issue.number).join(', ');
|
||||
qs('#my-work-action-status').textContent = keys + ' created and assigned to you.';
|
||||
const confirmed = result.confirmed[result.confirmed.length - 1];
|
||||
(result.filings || []).filter(filing => filing.relatedDraft?.checklistPromotion).forEach(filing => {
|
||||
void checklistPromotion?.finish(filing.issue, filing.relatedDraft.checklistPromotion);
|
||||
});
|
||||
const created = lastMyWork.find(item =>
|
||||
item.kind === 'issue' && item.repository === confirmed.repository && item.number === confirmed.number
|
||||
);
|
||||
@@ -5341,6 +5505,10 @@
|
||||
qs('#create-issue-title').focus();
|
||||
});
|
||||
qs('#cancel-new-issue').addEventListener('click', () => {
|
||||
if (checklistPromotion?.cancel()) {
|
||||
closeCreateIssueSheet(true, false);
|
||||
return;
|
||||
}
|
||||
const discardEditedDraft = Boolean(editingOutboxId);
|
||||
if (editingOutboxId) {
|
||||
issueCapture.clearDraft();
|
||||
@@ -5447,7 +5615,11 @@
|
||||
});
|
||||
async function admitReviewedIssue(review) {
|
||||
const durableDraft = review.draft;
|
||||
const deliveryDraft = {...durableDraft, relatedDraft:issueCapture.buildRelatedDraft(durableDraft)};
|
||||
const promotion = checklistPromotion?.deliveryContext();
|
||||
const deliveryDraft = {
|
||||
...durableDraft, relatedDraft:issueCapture.buildRelatedDraft(durableDraft),
|
||||
};
|
||||
if (promotion) deliveryDraft.relatedDraft.checklistPromotion = promotion;
|
||||
const followUpNextRequested = review.intent === 'follow-up-and-next';
|
||||
createAndStartRequested = review.intent === 'create-and-start';
|
||||
if (createAndStartRequested && !createAndStart.available()) {
|
||||
@@ -5598,10 +5770,63 @@
|
||||
});
|
||||
issueController.bindTaskToggles({
|
||||
container:qs('#issue-sheet-body'), status:qs('#issue-sheet-status'), retry:qs('#retry-issue-load'),
|
||||
current:()=>({item:selectedIssue,detail:selectedIssueDetail}),
|
||||
current:()=>({item:selectedIssue,detail:selectedIssueDetail,offline:selectedIssueOffline}),
|
||||
confirmed:applyIssueContent,
|
||||
restore:renderIssueBody,
|
||||
});
|
||||
const checklistStepManagement = issueController.bindTaskManagement({
|
||||
container:qs('#issue-sheet-body'), editor:qs('#checklist-step-editor'), label:qs('#checklist-step-label'),
|
||||
earlier:qs('#move-checklist-step-earlier'), later:qs('#move-checklist-step-later'),
|
||||
fileRelated:qs('#file-checklist-step-related'), onFileRelated:startChecklistPromotion,
|
||||
remove:qs('#remove-checklist-step'), cancel:qs('#cancel-checklist-step-edit'),
|
||||
status:qs('#checklist-step-edit-status'), sheetStatus:qs('#issue-sheet-status'), retry:qs('#retry-issue-load'),
|
||||
current:()=>({item:selectedIssue,detail:selectedIssueDetail,offline:selectedIssueOffline}),
|
||||
confirmed:applyIssueContent,
|
||||
});
|
||||
function closeAddChecklistStep() {
|
||||
qs('#add-checklist-step-form').hidden = true;
|
||||
qs('#add-checklist-step').value = '';
|
||||
qs('#open-add-checklist-step').focus();
|
||||
}
|
||||
qs('#open-add-checklist-step').addEventListener('click', () => {
|
||||
qs('#add-checklist-step-form').hidden = false;
|
||||
qs('#add-checklist-step-status').textContent = 'Add one required step.';
|
||||
qs('#add-checklist-step').focus();
|
||||
});
|
||||
qs('#cancel-checklist-step').addEventListener('click', closeAddChecklistStep);
|
||||
qs('#add-checklist-step-form').addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
const state = {item:selectedIssue, detail:selectedIssueDetail, offline:selectedIssueOffline};
|
||||
if (!state.item || !state.detail?.updated_at) return;
|
||||
const submit = qs('#save-checklist-step');
|
||||
submit.disabled = true;
|
||||
qs('#add-checklist-step-status').textContent = state.offline ? 'Queueing checklist step…' : 'Adding checklist step…';
|
||||
try {
|
||||
const result = await (selectedIssueOffline ? issueController.queueAddedTask : issueController.addTask).call(
|
||||
issueController, state.item, state.detail, qs('#add-checklist-step').value
|
||||
);
|
||||
if (selectedIssue !== state.item) return;
|
||||
applyIssueContent(state.item, state.detail, state.offline ? result.detail : result);
|
||||
closeAddChecklistStep();
|
||||
qs('#add-checklist-step-status').textContent = state.offline ?
|
||||
'Checklist step queued. Pending sync.' : 'Checklist step added.';
|
||||
} catch (error) {
|
||||
if (selectedIssue === state.item) {
|
||||
qs('#add-checklist-step-status').textContent = error.message;
|
||||
qs('#add-checklist-step').focus();
|
||||
}
|
||||
} finally {
|
||||
submit.disabled = false;
|
||||
}
|
||||
});
|
||||
qs('#complete-checklist-issue').addEventListener('click', () => {
|
||||
qs('#close-issue').click();
|
||||
});
|
||||
qs('#keep-checklist-issue-open').addEventListener('click', () => {
|
||||
dismissedChecklistBody = selectedIssueDetail?.body;
|
||||
if (selectedIssueDetail) renderChecklistCompletion(selectedIssueDetail);
|
||||
qs('#issue-sheet-body').focus();
|
||||
});
|
||||
qs('#issue-planning').addEventListener('toggle', event => {
|
||||
if (event.currentTarget.open) loadIssuePlanning();
|
||||
});
|
||||
@@ -6751,19 +6976,25 @@
|
||||
setStatus('Offline');
|
||||
if (!hasContextSnapshot) await hydrateOfflineWork();
|
||||
}
|
||||
function reconnectLiveData() {
|
||||
setStatus('Reconnecting…');
|
||||
contextPoller.refresh({ force: true }).then(snapshot => {
|
||||
const reconnectOutboxes = createReconnectOutboxes({
|
||||
refresh: async () => {
|
||||
setStatus('Reconnecting…');
|
||||
const snapshot = await contextPoller.refresh({ force: true });
|
||||
if (!snapshot) {
|
||||
offlineStatus.hidden = false;
|
||||
setOfflineWorkMode(true);
|
||||
return;
|
||||
return null;
|
||||
}
|
||||
offlineStatus.hidden = true;
|
||||
setOfflineWorkMode(false);
|
||||
if (selectedReview && offlineReview) openReviewSheet(selectedReview, reviewTrigger);
|
||||
});
|
||||
}
|
||||
return snapshot;
|
||||
},
|
||||
restoreIdentity: login => { activeFlushLogin = login; confirmedOwnerLogin = login; },
|
||||
flushIssue: flushIssueOutbox,
|
||||
flushAuthored: flushAuthoredOutbox,
|
||||
flushNotificationReads: flushNotificationReadOutbox,
|
||||
});
|
||||
async function setOfflineWorkEnabled(enabled) {
|
||||
keepWorkOffline.checked = enabled;
|
||||
offlineWorkStore.setEnabled(enabled);
|
||||
@@ -6821,7 +7052,7 @@
|
||||
updateDeliveryReceiptControls();
|
||||
if (!navigator.onLine) await showOfflineStatus();
|
||||
window.addEventListener('offline', showOfflineStatus);
|
||||
window.addEventListener('online', reconnectLiveData);
|
||||
window.addEventListener('online', reconnectOutboxes);
|
||||
|
||||
qs('#refresh').addEventListener('click', load);
|
||||
qs('#plan-today').addEventListener('click', event => openPlanToday(event.currentTarget));
|
||||
|
||||
+4
-1
@@ -155,6 +155,8 @@ function createDraftInbox({ storage, getCurrentLogin = () => '', now = () => Dat
|
||||
.filter(Boolean).join('\n\n');
|
||||
const ownerLogin = String(item.ownerLogin || '').trim();
|
||||
const quarantined = !ownerLogin || !currentLogin || ownerLogin !== currentLogin;
|
||||
const checklistConflict = !quarantined && item.kind === 'issue-content' &&
|
||||
item.status === 'attention' && typeof item.baseBody === 'string';
|
||||
return {
|
||||
id: 'stackchain.authored-outbox.v1:' + item.id,
|
||||
outbox_id: item.id,
|
||||
@@ -162,7 +164,7 @@ function createDraftInbox({ storage, getCurrentLogin = () => '', now = () => Dat
|
||||
kind: 'authored-outbox',
|
||||
status: item.status === 'attention' ? 'attention' : (item.status === 'sending' ? 'sending' :
|
||||
(item.status === 'authorization' || isClosure ? 'authorization' : 'queued')),
|
||||
label: item.deliveryState === 'uncertain' ? 'Verify delivery' :
|
||||
label: checklistConflict ? 'Checklist conflict' : item.deliveryState === 'uncertain' ? 'Verify delivery' :
|
||||
(item.status === 'attention' ? (isClosure ? 'Issue closure needs attention' : 'Needs attention') :
|
||||
(isReview ? (item.status === 'authorization' ? 'Review awaiting authorization' : 'Queued review') :
|
||||
(isClosure ? 'Awaiting authorization' : 'Queued message'))),
|
||||
@@ -172,6 +174,7 @@ function createDraftInbox({ storage, getCurrentLogin = () => '', now = () => Dat
|
||||
title: target,
|
||||
preview: textPreview([item.error, item.body].filter(Boolean).join(' — ')),
|
||||
copy_text: copyText,
|
||||
checklist_conflict: checklistConflict,
|
||||
...(isReview ? { head_sha: item.expectedHeadSha } : {}),
|
||||
quarantined,
|
||||
ownership: quarantined ? 'Queued by ' + (ownerLogin || 'an unknown account') +
|
||||
|
||||
+56
-1
@@ -600,11 +600,42 @@
|
||||
<div id="issue-sheet-status" class="small" aria-live="polite">Choose an issue.</div>
|
||||
<section class="completed-filed-actions" id="completed-filed-actions" aria-label="Completed Filed review" hidden>
|
||||
<span id="completed-filed-progress" role="status" aria-live="polite">Completed Filed issue ready for review.</span>
|
||||
<button id="acknowledge-completed-filed" type="button">Acknowledge & next</button>
|
||||
<div class="completed-filed-buttons">
|
||||
<button id="complete-parent-and-acknowledge" type="button" hidden>Complete parent step & acknowledge</button>
|
||||
<button id="acknowledge-completed-filed" type="button">Acknowledge & next</button>
|
||||
</div>
|
||||
</section>
|
||||
<button class="issue-retry" id="retry-issue-load" type="button" hidden>Reload latest issue</button>
|
||||
<div class="row"><span id="issue-labels"></span><span class="small" id="issue-assignees"></span></div>
|
||||
<div class="issue-sheet-content markdown-content" id="issue-sheet-body"></div>
|
||||
<form class="checklist-step-editor" id="checklist-step-editor" aria-label="Manage checklist step" hidden>
|
||||
<label for="checklist-step-label">Checklist step</label>
|
||||
<input id="checklist-step-label" type="text" maxlength="240" autocomplete="off" />
|
||||
<div class="checklist-step-editor-actions">
|
||||
<button id="save-checklist-step-edit" type="submit">Rename</button>
|
||||
<button id="move-checklist-step-earlier" type="button">Move earlier</button>
|
||||
<button id="move-checklist-step-later" type="button">Move later</button>
|
||||
<button id="file-checklist-step-related" type="button">File as related issue</button>
|
||||
<button id="remove-checklist-step" type="button">Remove</button>
|
||||
<button id="cancel-checklist-step-edit" type="button">Cancel</button>
|
||||
</div>
|
||||
<div id="checklist-step-edit-status" class="small" aria-live="assertive"></div>
|
||||
</form>
|
||||
<section class="checklist-add" aria-label="Add checklist step">
|
||||
<button id="open-add-checklist-step" type="button" disabled>Add step</button>
|
||||
<form id="add-checklist-step-form" hidden>
|
||||
<label class="visually-hidden" for="add-checklist-step">Checklist step</label>
|
||||
<input id="add-checklist-step" type="text" maxlength="240" autocomplete="off" placeholder="New checklist step" />
|
||||
<button id="save-checklist-step" type="submit">Add</button>
|
||||
<button id="cancel-checklist-step" type="button">Cancel</button>
|
||||
</form>
|
||||
<div id="add-checklist-step-status" class="small" aria-live="assertive"></div>
|
||||
</section>
|
||||
<section class="checklist-completion" id="checklist-completion" aria-label="Completed checklist" hidden>
|
||||
<span id="checklist-completion-status" role="status" aria-live="polite">Checklist complete</span>
|
||||
<button id="complete-checklist-issue" type="button">Close issue</button>
|
||||
<button id="keep-checklist-issue-open" type="button">Keep open</button>
|
||||
</section>
|
||||
<section class="issue-blockers" id="issue-blockers" aria-labelledby="issue-blockers-title" hidden>
|
||||
<h2 id="issue-blockers-title">Blocked by</h2>
|
||||
<div class="issue-blocker-list" id="issue-blocker-list"></div>
|
||||
@@ -785,6 +816,27 @@
|
||||
<label for="create-issue-body">Note <span class="small">Optional</span>
|
||||
<textarea id="create-issue-body" maxlength="10000"></textarea>
|
||||
</label>
|
||||
<section class="voice-issue-capture" id="voice-issue-capture" aria-labelledby="voice-issue-heading" hidden>
|
||||
<div class="voice-issue-heading">
|
||||
<strong id="voice-issue-heading">Speak capture</strong>
|
||||
<span class="small">Your browser transcribes speech. Stackchain does not retain audio.</span>
|
||||
</div>
|
||||
<div class="voice-issue-controls">
|
||||
<button id="start-voice-issue-capture" type="button">Speak capture</button>
|
||||
<button id="stop-voice-issue-capture" type="button" hidden>Stop listening</button>
|
||||
</div>
|
||||
<div id="voice-issue-status" class="small" aria-live="polite"></div>
|
||||
<div class="voice-issue-review" id="voice-issue-review" hidden>
|
||||
<label for="voice-issue-transcript">Review transcript
|
||||
<textarea id="voice-issue-transcript" maxlength="10255"></textarea>
|
||||
</label>
|
||||
<div class="voice-issue-review-actions">
|
||||
<button id="append-voice-issue-transcript" type="button">Append to draft</button>
|
||||
<button id="replace-with-voice-issue-transcript" type="button">Replace draft</button>
|
||||
<button id="discard-voice-issue-transcript" type="button" class="secondary">Discard transcript</button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<div class="create-issue-capture-actions">
|
||||
<button id="save-unfiled-issue" type="button">Save to Drafts</button>
|
||||
<button id="file-new-issue" type="button">File now</button>
|
||||
@@ -1276,6 +1328,7 @@
|
||||
<script src="static/outbox-coordinator.js"></script>
|
||||
<script src="static/background-issue-sync.js"></script>
|
||||
<script src="static/issue-outbox.js"></script>
|
||||
<script src="static/reconnect-outboxes.js"></script>
|
||||
<script src="static/authored-outbox.js"></script>
|
||||
<script src="static/offline-issue-close.js"></script>
|
||||
<script src="static/offline-issue-blocker.js"></script>
|
||||
@@ -1317,6 +1370,8 @@
|
||||
<script src="static/issue-attachment.js"></script>
|
||||
<script src="static/issue-filing-review.js"></script>
|
||||
<script src="static/issue-sheet.js"></script>
|
||||
<script src="static/voice-transcript-store.js"></script>
|
||||
<script src="static/voice-issue-capture.js"></script>
|
||||
<script src="static/create-issue-sheet.js"></script>
|
||||
<script src="static/create-and-start.js"></script>
|
||||
<script src="static/assign-and-start.js"></script>
|
||||
|
||||
@@ -76,6 +76,14 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
|
||||
plan.templateName = String(value?.templateName || 'Issue template').trim().slice(0, 80);
|
||||
plan.capturedBody = '';
|
||||
}
|
||||
const promotion = value?.checklistPromotion;
|
||||
if (promotion?.repository && promotion?.number && promotion?.url && promotion?.updatedAt) {
|
||||
plan.checklistPromotion = {
|
||||
repository:String(promotion.repository), number:Number(promotion.number), url:String(promotion.url),
|
||||
title:String(promotion.title || ''), body:String(promotion.body || '').slice(0, 10000),
|
||||
updatedAt:String(promotion.updatedAt), taskIndex:Number(promotion.taskIndex),
|
||||
};
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
@@ -134,6 +142,7 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
|
||||
if (blockers) item.blockers = blockers;
|
||||
const relatedDraft = captureRelatedDraft(draft?.relatedDraft);
|
||||
if (relatedDraft) item.relatedDraft = relatedDraft;
|
||||
|
||||
item.operationId = item.id;
|
||||
if (Number.isInteger(Number(draft?.milestoneId)) && Number(draft.milestoneId) > 0) {
|
||||
item.milestoneId = Number(draft.milestoneId);
|
||||
@@ -496,6 +505,7 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
|
||||
const confirmed = [];
|
||||
const completions = [];
|
||||
const filings = [];
|
||||
|
||||
let blocked = 0;
|
||||
currentLogin = String(currentLogin || '').trim();
|
||||
for (const item of read()) {
|
||||
@@ -505,6 +515,7 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
|
||||
if (result.issue) {
|
||||
confirmed.push(result.issue);
|
||||
if (result.item?.relatedDraft) filings.push({issue:result.issue, relatedDraft:result.item.relatedDraft});
|
||||
|
||||
if (result.item?.completionIntent) completions.push({
|
||||
id: result.item.id,
|
||||
intent: result.item.completionIntent,
|
||||
@@ -546,6 +557,7 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
|
||||
return {
|
||||
confirmed: result.issue ? [result.issue] : [],
|
||||
filings: result.issue && result.item?.relatedDraft ? [{issue:result.issue, relatedDraft:result.item.relatedDraft}] : [],
|
||||
|
||||
completions: result.issue && result.item?.completionIntent ? [{
|
||||
id: result.item.id,
|
||||
intent: result.item.completionIntent,
|
||||
|
||||
+295
-7
@@ -24,7 +24,135 @@ function escapeOptionHtml(value) {
|
||||
})[character]);
|
||||
}
|
||||
|
||||
function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.renderMarkdown, toggleTask = renderMarkdown?.toggleTask, createConversationPager = globalThis.createConversationPager, createOperationId = () => globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random() }) {
|
||||
function appendChecklistTask(body, label) {
|
||||
const normalized = String(label || '').trim().replace(/\s+/g, ' ');
|
||||
if (!normalized) throw new Error('Enter a checklist step.');
|
||||
const key = normalized.toLocaleLowerCase();
|
||||
const duplicate = String(body || '').split('\n').some(line => {
|
||||
const match = line.match(/^\s*[-*+]\s+\[[ xX]\]\s+(.*)$/);
|
||||
return match && match[1].trim().replace(/\s+/g, ' ').toLocaleLowerCase() === key;
|
||||
});
|
||||
if (duplicate) throw new Error('That checklist step already exists.');
|
||||
const prefix = body ? String(body).replace(/\s+$/, '') + '\n' : '';
|
||||
return prefix + '- [ ] ' + normalized;
|
||||
}
|
||||
|
||||
function manageChecklistTask(raw, targetIndex, operation = {}) {
|
||||
const parts = String(raw || '').split(/(\r\n|\n|\r)/);
|
||||
let fenced = false;
|
||||
let taskIndex = 0;
|
||||
for (let index = 0; index < parts.length; index += 2) {
|
||||
const line = parts[index];
|
||||
if (/^\s*```/.test(line)) { fenced = !fenced; continue; }
|
||||
if (fenced) continue;
|
||||
const task = line.match(/^([-*+]\s+\[[ xX]\]\s+)(.*)$/);
|
||||
if (!task) continue;
|
||||
if (taskIndex === Number(targetIndex)) {
|
||||
if (operation.action === 'rename') {
|
||||
const label = String(operation.label || '').trim().replace(/\s+/g, ' ');
|
||||
if (!label) throw new Error('Enter a checklist step.');
|
||||
const key = label.toLocaleLowerCase();
|
||||
let inFence = false;
|
||||
const duplicate = parts.some((candidate, candidateIndex) => {
|
||||
if (candidateIndex % 2) return false;
|
||||
if (/^\s*```/.test(candidate)) { inFence = !inFence; return false; }
|
||||
if (inFence || candidateIndex === index) return false;
|
||||
const match = candidate.match(/^[-*+]\s+\[[ xX]\]\s+(.*)$/);
|
||||
return match && match[1].trim().replace(/\s+/g, ' ').toLocaleLowerCase() === key;
|
||||
});
|
||||
if (duplicate) throw new Error('That checklist step already exists.');
|
||||
parts[index] = task[1] + label;
|
||||
} else if (operation.action === 'remove') {
|
||||
if (index + 1 < parts.length) parts.splice(index, 2);
|
||||
else if (index > 0) parts.splice(index - 1, 2);
|
||||
} else if (operation.action === 'move-earlier' && index >= 2 && /^(\s*[-*+]\s+\[[ xX]\]\s+)/.test(parts[index - 2])) {
|
||||
[parts[index - 2], parts[index]] = [parts[index], parts[index - 2]];
|
||||
} else if (operation.action === 'move-later' && index + 2 < parts.length && /^(\s*[-*+]\s+\[[ xX]\]\s+)/.test(parts[index + 2])) {
|
||||
[parts[index], parts[index + 2]] = [parts[index + 2], parts[index]];
|
||||
}
|
||||
return parts.join('');
|
||||
}
|
||||
taskIndex += 1;
|
||||
}
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
function checklistIsComplete(raw) {
|
||||
const lines = String(raw || '').split(/(?:\r\n|\n|\r)/);
|
||||
let fenced = false;
|
||||
let found = false;
|
||||
for (const line of lines) {
|
||||
if (/^\s*```/.test(line)) { fenced = !fenced; continue; }
|
||||
if (fenced) continue;
|
||||
const task = line.match(/^\s*[-*+]\s+\[([ xX])\]\s+/);
|
||||
if (!task) continue;
|
||||
found = true;
|
||||
if (task[1].toLocaleLowerCase() !== 'x') return false;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
function completeDelegatedParentTask(raw, childUrl) {
|
||||
const url = String(childUrl || '');
|
||||
if (!/^https:\/\/[^\s)]+$/.test(url)) throw new Error('The delegated issue link is unavailable.');
|
||||
const parts = String(raw || '').split(/(\r\n|\n|\r)/);
|
||||
let fenced = false;
|
||||
let taskIndex = 0;
|
||||
for (let index = 0; index < parts.length; index += 2) {
|
||||
const line = parts[index];
|
||||
if (/^\s*```/.test(line)) { fenced = !fenced; continue; }
|
||||
if (fenced) continue;
|
||||
const task = line.match(/^(\s*[-*+]\s+\[)([ xX])(\]\s+.*)$/);
|
||||
if (!task) continue;
|
||||
const linkedTask = task[3].match(/^\]\s+\[[^\]]+\]\((https:\/\/[^\s)]+)\)\s*$/);
|
||||
if (linkedTask?.[1] === url) {
|
||||
const alreadyCompleted = task[2].toLocaleLowerCase() === 'x';
|
||||
if (!alreadyCompleted) parts[index] = task[1] + 'x' + task[3];
|
||||
const body = parts.join('');
|
||||
return { body, taskIndex, alreadyCompleted, checklistComplete:checklistIsComplete(body) };
|
||||
}
|
||||
taskIndex += 1;
|
||||
}
|
||||
throw new Error('The parent checklist no longer links to this delegated issue.');
|
||||
}
|
||||
|
||||
async function finishDelegatedParentReview({ parentItem, parentDetail, childUrl, updateContent, closeParent }) {
|
||||
const completion = completeDelegatedParentTask(parentDetail?.body, childUrl);
|
||||
if (!completion.alreadyCompleted) {
|
||||
await updateContent(parentItem, {
|
||||
title:parentDetail.title,
|
||||
body:completion.body,
|
||||
expectedUpdatedAt:parentDetail.updated_at,
|
||||
});
|
||||
}
|
||||
if (completion.checklistComplete) await closeParent(parentItem);
|
||||
return { updated:!completion.alreadyCompleted, closed:completion.checklistComplete };
|
||||
}
|
||||
|
||||
function delegatedParentReference(childDetail) {
|
||||
const body = String(childDetail?.body || '');
|
||||
const match = body.match(/(?:^|\n)Related to \[([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)#([1-9]\d*)\]\((https:\/\/[^\s)]+)\)\.(?:\r?$|\s)/m);
|
||||
if (!match) return null;
|
||||
return { repository:match[1], number:Number(match[2]), url:match[3] };
|
||||
}
|
||||
|
||||
function resolveDelegatedParent(child, childDetail, parentDetail) {
|
||||
const parent = delegatedParentReference(childDetail);
|
||||
if (!parent) return null;
|
||||
try {
|
||||
const completion = completeDelegatedParentTask(parentDetail?.body, child?.url);
|
||||
return {
|
||||
parent,
|
||||
taskIndex:completion.taskIndex,
|
||||
alreadyCompleted:completion.alreadyCompleted,
|
||||
checklistComplete:completion.checklistComplete,
|
||||
};
|
||||
} catch (_error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.renderMarkdown, toggleTask = renderMarkdown?.toggleTask, manageTask: manageTaskTransform = manageChecklistTask, relatedTaskDraft: relatedTaskDraftTransform = (...args) => globalThis.createIssueCapture?.relatedChecklistDraft(...args), linkRelatedTask: linkRelatedTaskTransform = (...args) => globalThis.createIssueCapture?.linkChecklistTask(...args), enqueueDurably, createConversationPager = globalThis.createConversationPager, createOperationId = () => globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random() }) {
|
||||
let commentRequest = null;
|
||||
let closeRequest = null;
|
||||
let releaseRequest = null;
|
||||
@@ -45,6 +173,9 @@ function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.rend
|
||||
const milestoneDraftKey = item => 'stackchain.issue-milestone.v1:' + item.repository + '#' + item.number;
|
||||
|
||||
return {
|
||||
delegatedParentReference,
|
||||
resolveDelegatedParent,
|
||||
completeDelegatedParentTask,
|
||||
readOnly(item) {
|
||||
return Boolean(item?.is_completed || (item?.is_filed && !item?.is_assigned));
|
||||
},
|
||||
@@ -152,6 +283,72 @@ function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.rend
|
||||
expectedUpdatedAt: detail.updated_at,
|
||||
});
|
||||
},
|
||||
manageTask(item, detail, taskIndex, operation) {
|
||||
if (typeof manageTaskTransform !== 'function') return Promise.reject(new Error('Checklist management is unavailable.'));
|
||||
return this.updateContent(item, {
|
||||
title: detail.title,
|
||||
body: manageTaskTransform(detail.body, taskIndex, operation),
|
||||
expectedUpdatedAt: detail.updated_at,
|
||||
});
|
||||
},
|
||||
relatedTaskDraft(item, _detail, _taskIndex, label) {
|
||||
if (typeof relatedTaskDraftTransform !== 'function') throw new Error('Related issue capture is unavailable.');
|
||||
return relatedTaskDraftTransform(item, label);
|
||||
},
|
||||
linkRelatedTask(item, detail, taskIndex, child) {
|
||||
if (typeof linkRelatedTaskTransform !== 'function') return Promise.reject(new Error('Related issue linking is unavailable.'));
|
||||
return this.updateContent(item, {
|
||||
title:detail.title,
|
||||
body:linkRelatedTaskTransform(detail.body, taskIndex, child),
|
||||
expectedUpdatedAt:detail.updated_at,
|
||||
});
|
||||
},
|
||||
async addTask(item, detail, label) {
|
||||
const body = appendChecklistTask(detail.body, label);
|
||||
return this.updateContent(item, {
|
||||
title: detail.title,
|
||||
body,
|
||||
expectedUpdatedAt: detail.updated_at,
|
||||
});
|
||||
},
|
||||
async queueAddedTask(item, detail, label) {
|
||||
if (typeof enqueueDurably !== 'function') {
|
||||
throw new Error('Offline checklist updates are unavailable.');
|
||||
}
|
||||
const body = appendChecklistTask(detail.body, label);
|
||||
await enqueueDurably({ kind:'issue-content', repository:item.repository, number:item.number,
|
||||
title:detail.title, baseBody:detail.body, body, expectedUpdatedAt:detail.updated_at });
|
||||
return { queued:true, detail:{ ...detail, body, checklist_pending:true } };
|
||||
},
|
||||
async queueManagedTask(item, detail, taskIndex, operation) {
|
||||
if (typeof manageTaskTransform !== 'function' || typeof enqueueDurably !== 'function') {
|
||||
throw new Error('Offline checklist management is unavailable.');
|
||||
}
|
||||
const body = manageTaskTransform(detail.body, taskIndex, operation);
|
||||
const checklistOperation = {
|
||||
action:String(operation?.action || ''), index:Number(taskIndex),
|
||||
...(operation?.label ? { label:String(operation.label) } : {}),
|
||||
};
|
||||
await enqueueDurably({ kind:'issue-content', repository:item.repository, number:item.number,
|
||||
title:detail.title, baseBody:detail.body, body, expectedUpdatedAt:detail.updated_at, checklistOperation });
|
||||
return { queued:true, detail:{ ...detail, body, checklist_pending:true } };
|
||||
},
|
||||
async queueTask(item, detail, taskIndex, checked) {
|
||||
if (typeof toggleTask !== 'function' || typeof enqueueDurably !== 'function') {
|
||||
throw new Error('Offline checklist updates are unavailable.');
|
||||
}
|
||||
const body = toggleTask(detail.body, taskIndex, checked);
|
||||
await enqueueDurably({ kind:'issue-content', repository:item.repository, number:item.number,
|
||||
title:detail.title, baseBody:detail.body, body, expectedUpdatedAt:detail.updated_at });
|
||||
return { queued:true, detail:{ ...detail, body, checklist_pending:true } };
|
||||
},
|
||||
pendingTask(item, detail, items, ownerLogin) {
|
||||
const pending = [...(items || [])].reverse().find(candidate => candidate?.kind === 'issue-content' &&
|
||||
candidate.repository === item?.repository && Number(candidate.number) === Number(item?.number) &&
|
||||
candidate.ownerLogin === ownerLogin && ['queued', 'sending', 'attention'].includes(candidate.status));
|
||||
if (!pending) return { ...detail };
|
||||
return { ...detail, title:pending.title, body:pending.body, checklist_pending:true };
|
||||
},
|
||||
bindTaskToggles({ container, status, retry, current, confirmed, restore }) {
|
||||
container.addEventListener('change', async event => {
|
||||
const control = event.target.closest('input.task-list-toggle');
|
||||
@@ -161,13 +358,14 @@ function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.rend
|
||||
container.querySelectorAll('input.task-list-toggle').forEach(input => { input.disabled = true; });
|
||||
status.textContent = 'Updating checklist…';
|
||||
try {
|
||||
const result = await this.toggleTask(
|
||||
state.item, state.detail, Number(control.dataset.taskIndex), control.checked
|
||||
const result = await (state.offline ? this.queueTask : this.toggleTask).call(
|
||||
this, state.item, state.detail, Number(control.dataset.taskIndex), control.checked
|
||||
);
|
||||
const latest = current();
|
||||
if (latest?.item?.repository === state.item.repository && latest.item.number === state.item.number) {
|
||||
confirmed(state.item, state.detail, result);
|
||||
status.textContent = 'Checklist updated.';
|
||||
confirmed(state.item, state.detail, state.offline ? result.detail : result);
|
||||
if (state.offline) status.textContent = 'Checklist queued. Pending sync.';
|
||||
else status.textContent = 'Checklist updated.';
|
||||
}
|
||||
} catch (error) {
|
||||
const latest = current();
|
||||
@@ -179,12 +377,97 @@ function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.rend
|
||||
}
|
||||
});
|
||||
},
|
||||
bindTaskManagement({ container, editor, label, earlier, later, fileRelated, onFileRelated, remove, cancel, status, sheetStatus, retry, current, confirmed }) {
|
||||
let taskIndex = null;
|
||||
let trigger = null;
|
||||
const reset = (returnFocus = false) => {
|
||||
editor.hidden = true;
|
||||
status.textContent = '';
|
||||
if (returnFocus && trigger?.isConnected) trigger.focus();
|
||||
taskIndex = null;
|
||||
trigger = null;
|
||||
};
|
||||
container.addEventListener('click', event => {
|
||||
const control = event.target.closest('button.task-list-manage');
|
||||
if (!control || !current()?.detail?.updated_at) return;
|
||||
taskIndex = Number(control.dataset.taskIndex);
|
||||
trigger = control;
|
||||
label.value = control.dataset.taskLabel || '';
|
||||
earlier.disabled = control.dataset.taskFirst === 'true';
|
||||
later.disabled = control.dataset.taskLast === 'true';
|
||||
fileRelated.disabled = /^\s*\[[^\]]+\]\([^)]+\)\s*$/.test(label.value);
|
||||
editor.hidden = false;
|
||||
status.textContent = fileRelated.disabled ? 'This step already links to related work.' :
|
||||
'Rename, reorder, remove, or file this step as related work.';
|
||||
label.focus();
|
||||
});
|
||||
const run = async operation => {
|
||||
const state = current();
|
||||
const selectedIndex = taskIndex;
|
||||
if (!state?.item || !state.detail?.updated_at || selectedIndex === null) return;
|
||||
if (operation.action === 'remove' && !globalThis.confirm('Remove this checklist step?')) return;
|
||||
const controls = editor.querySelectorAll('button,input');
|
||||
controls.forEach(control => { control.disabled = true; });
|
||||
status.textContent = state.offline ? 'Queueing checklist change…' : 'Updating checklist…';
|
||||
try {
|
||||
const result = await (state.offline ? this.queueManagedTask : this.manageTask).call(
|
||||
this, state.item, state.detail, selectedIndex, operation
|
||||
);
|
||||
if (current()?.item !== state.item) return;
|
||||
confirmed(state.item, state.detail, state.offline ? result.detail : result);
|
||||
reset();
|
||||
sheetStatus.textContent = state.offline ? 'Checklist change queued. Pending sync.' : 'Checklist step updated.';
|
||||
const focusIndex = operation.action === 'remove' ? Math.max(0, selectedIndex - 1) : selectedIndex;
|
||||
container.querySelector('button.task-list-manage[data-task-index="' + focusIndex + '"]')?.focus();
|
||||
} catch (error) {
|
||||
if (current()?.item === state.item) {
|
||||
status.textContent = error.message + ' Your change is still here; retry.';
|
||||
retry.hidden = false;
|
||||
label.focus();
|
||||
}
|
||||
} finally {
|
||||
if (!editor.hidden) controls.forEach(control => { control.disabled = false; });
|
||||
}
|
||||
};
|
||||
editor.addEventListener('submit', event => { event.preventDefault(); run({ action:'rename', label:label.value }); });
|
||||
earlier.addEventListener('click', () => run({ action:'move-earlier' }));
|
||||
later.addEventListener('click', () => run({ action:'move-later' }));
|
||||
fileRelated.addEventListener('click', async () => {
|
||||
const state = current();
|
||||
const selectedIndex = taskIndex;
|
||||
if (!state?.item || !state.detail?.updated_at || selectedIndex === null || fileRelated.disabled) return;
|
||||
try {
|
||||
await onFileRelated({ item:state.item, detail:state.detail, taskIndex:selectedIndex,
|
||||
label:label.value, trigger });
|
||||
reset();
|
||||
} catch (error) {
|
||||
status.textContent = error.message + ' The checklist step was not changed.';
|
||||
label.focus();
|
||||
}
|
||||
});
|
||||
remove.addEventListener('click', () => run({ action:'remove' }));
|
||||
cancel.addEventListener('click', () => reset(true));
|
||||
return { reset };
|
||||
},
|
||||
renderTasks(container, detail, interactive) {
|
||||
container.classList.remove('checklist-pending');
|
||||
container.classList.toggle('checklist-pending', detail.checklist_pending === true);
|
||||
container.innerHTML = renderMarkdown(
|
||||
detail.body || 'No description provided.', { interactiveTasks: Boolean(interactive) }
|
||||
detail.body || 'No description provided.', {
|
||||
interactiveTasks: Boolean(interactive),
|
||||
manageTasks: Boolean(interactive),
|
||||
}
|
||||
);
|
||||
},
|
||||
checklistCompletion(container, { interactive, today, offline, dismissed = false }) {
|
||||
const tasks = Array.from(container.querySelectorAll('input.task-list-toggle'));
|
||||
const visible = Boolean(interactive && !dismissed && tasks.length && tasks.every(task => task.checked));
|
||||
return {
|
||||
visible,
|
||||
status: offline ? 'Checklist complete · pending sync' : 'Checklist complete',
|
||||
label: today ? (offline ? 'Queue close & next' : 'Close & next') :
|
||||
(offline ? 'Queue issue closure' : 'Close issue'),
|
||||
};
|
||||
},
|
||||
mergeContent(snapshot, item, detail, confirmed, replace) {
|
||||
return {
|
||||
snapshot: snapshot ? replace(snapshot, item.repository, item.number, confirmed) : snapshot,
|
||||
@@ -379,4 +662,9 @@ function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.rend
|
||||
|
||||
createIssueSheet.createPlanningLoader = createPlanningLoader;
|
||||
|
||||
createIssueSheet.manageChecklistTask = manageChecklistTask;
|
||||
createIssueSheet.completeDelegatedParentTask = completeDelegatedParentTask;
|
||||
createIssueSheet.finishDelegatedParentReview = finishDelegatedParentReview;
|
||||
createIssueSheet.delegatedParentReference = delegatedParentReference;
|
||||
createIssueSheet.resolveDelegatedParent = resolveDelegatedParent;
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createIssueSheet;
|
||||
@@ -43,8 +43,13 @@
|
||||
' class="task-list-toggle" data-task-index="' + (firstTaskIndex + offset) +
|
||||
'" aria-label="Mark ' + escapeHtml(body) + (checked ? ' incomplete"' : ' complete"') :
|
||||
' disabled';
|
||||
const manage = options.interactiveTasks && options.manageTasks ?
|
||||
'<button type="button" class="task-list-manage" data-task-index="' + (firstTaskIndex + offset) +
|
||||
'" data-task-label="' + escapeHtml(body) + '" aria-label="Manage step: ' + escapeHtml(body) + '"' +
|
||||
(offset === 0 ? ' data-task-first="true"' : '') +
|
||||
(offset === lines.length - 1 ? ' data-task-last="true"' : '') + '>Manage</button>' : '';
|
||||
return '<li class="task-list-item"><input type="checkbox"' + control +
|
||||
(checked ? ' checked' : '') + '> ' + renderInline(body) + '</li>';
|
||||
(checked ? ' checked' : '') + '> ' + renderInline(body) + manage + '</li>';
|
||||
}).join('');
|
||||
return '<ul' + (taskList ? ' class="task-list"' : '') + '>' + items + '</ul>';
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
'stackchain-background-outbox-v1',
|
||||
'stackchain-offline-work-v2',
|
||||
'stackchain-unfiled-captures-v1',
|
||||
'stackchain-voice-transcripts-v1',
|
||||
]);
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = databases;
|
||||
else root.stackchainPrivateDatabases = databases;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
function createReconnectOutboxes({
|
||||
refresh,
|
||||
restoreIdentity,
|
||||
flushIssue,
|
||||
flushAuthored,
|
||||
flushNotificationReads,
|
||||
}) {
|
||||
return async function reconnectOutboxes() {
|
||||
const snapshot = await refresh();
|
||||
const freshness = snapshot?.freshness?.sections?.context;
|
||||
const identityFresh = snapshot?.context && !snapshot.context.error &&
|
||||
!freshness?.stale && !freshness?.degraded && !freshness?.revalidating;
|
||||
const login = identityFresh ? String(snapshot.context.user?.login || '').trim() : '';
|
||||
if (!login) return false;
|
||||
restoreIdentity(login);
|
||||
await Promise.all([
|
||||
flushIssue(),
|
||||
flushAuthored(),
|
||||
flushNotificationReads(),
|
||||
]);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createReconnectOutboxes;
|
||||
@@ -1,7 +1,7 @@
|
||||
const BASE = new URL('./', self.location.href).pathname;
|
||||
importScripts(BASE + 'static/private-data-registry.js');
|
||||
importScripts(BASE + 'static/background-issue-sync.js');
|
||||
const CACHE = 'stackchain-dashboard-shell-v107';
|
||||
const CACHE = 'stackchain-dashboard-shell-v108';
|
||||
const OFFLINE_LEASE_URL = new URL(BASE + '__offline-session-lease', self.location.origin).href;
|
||||
const OUTAGE_STATUSES = new Set([500, 502, 503, 504]);
|
||||
const NAVIGATION_TIMEOUT_MS = self.__STACKCHAIN_NAVIGATION_TIMEOUT_MS || 4000;
|
||||
@@ -32,6 +32,7 @@ const SHELL = [
|
||||
BASE + 'static/draft-capacity-dialog.js',
|
||||
BASE + 'static/outbox-coordinator.js',
|
||||
BASE + 'static/issue-outbox.js',
|
||||
BASE + 'static/reconnect-outboxes.js',
|
||||
BASE + 'static/authored-outbox.js',
|
||||
BASE + 'static/offline-issue-close.js',
|
||||
BASE + 'static/offline-issue-blocker.js',
|
||||
@@ -73,6 +74,9 @@ const SHELL = [
|
||||
BASE + 'static/issue-attachment.js',
|
||||
BASE + 'static/issue-filing-review.js',
|
||||
BASE + 'static/issue-sheet.js',
|
||||
BASE + 'static/checklist-conflict.js',
|
||||
BASE + 'static/voice-transcript-store.js',
|
||||
BASE + 'static/voice-issue-capture.js',
|
||||
BASE + 'static/create-issue-sheet.js',
|
||||
BASE + 'static/create-and-start.js',
|
||||
BASE + 'static/assign-and-start.js',
|
||||
|
||||
@@ -36,6 +36,7 @@
|
||||
root.fetch = boundary.fetch;
|
||||
const attach = () => {
|
||||
boundary.startActivityHeartbeat();
|
||||
boundary.startReconnectResume();
|
||||
const button = root.document.getElementById('sign-out');
|
||||
if (button) button.addEventListener('click', () => boundary.signOut());
|
||||
const allDevicesButton = root.document.getElementById('sign-out-all');
|
||||
@@ -387,6 +388,12 @@
|
||||
});
|
||||
}
|
||||
|
||||
function startReconnectResume() {
|
||||
addActivityListener?.('online', async () => {
|
||||
if (await refreshOfflineLease()) await resumeQueuedWork();
|
||||
});
|
||||
}
|
||||
|
||||
async function refreshOfflineLease() {
|
||||
try {
|
||||
const response = await sessionFetch(base + 'api/v1/session');
|
||||
@@ -617,6 +624,7 @@
|
||||
handleServiceWorkerMessage,
|
||||
refreshOfflineLease,
|
||||
resumeQueuedWork,
|
||||
startReconnectResume,
|
||||
recordActivity,
|
||||
startActivityHeartbeat,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
function mapVoiceTranscript(value) {
|
||||
const transcript = String(value || '').replace(/\s+/g, ' ').trim();
|
||||
if (!transcript) return {title:'', body:''};
|
||||
const sentence = transcript.match(/^(.+?[.!?])(?:\s+|$)(.*)$/);
|
||||
const title = (sentence ? sentence[1] : transcript).trim().slice(0, 255);
|
||||
const body = (sentence ? sentence[2] : '').trim().slice(0, 10000);
|
||||
return {title, body};
|
||||
}
|
||||
|
||||
function createVoiceIssueCapture({
|
||||
Recognition, elements, createEvent = name => new Event(name, {bubbles:true}),
|
||||
transcriptStore = null, getLogin = () => '',
|
||||
}) {
|
||||
const supported = typeof Recognition === 'function';
|
||||
const login = String(getLogin() || '').trim();
|
||||
const ready = supported && login && transcriptStore ? Promise.resolve(transcriptStore.load(login)).then(value => {
|
||||
const recovered = String(value || '').replace(/\s+/g, ' ').trim().slice(0, 10255);
|
||||
if (recovered) showReview(recovered, {persist:false, recovered:true});
|
||||
}) : Promise.resolve();
|
||||
elements.root.hidden = !supported;
|
||||
if (!supported) {
|
||||
elements.status.textContent = 'Voice capture is unavailable; type the title and note instead.';
|
||||
return {supported:false, ready, cancel() {}};
|
||||
}
|
||||
let recognition = null;
|
||||
|
||||
function showReview(value, {persist = true, recovered = false} = {}) {
|
||||
elements.transcript.value = value;
|
||||
const activeLogin = String(getLogin() || '').trim();
|
||||
if (persist && activeLogin && transcriptStore) void transcriptStore.save(activeLogin, value);
|
||||
const hasDraft = Boolean(elements.title.value.trim() || elements.body.value.trim());
|
||||
elements.append.textContent = hasDraft ? 'Append to draft' : 'Use transcript';
|
||||
elements.replace.hidden = !hasDraft;
|
||||
elements.review.hidden = false;
|
||||
elements.status.textContent = recovered ?
|
||||
'Recovered transcript. Review it before using or discarding it.' :
|
||||
'Transcript ready. Review it before using it.';
|
||||
}
|
||||
|
||||
elements.start.addEventListener('click', () => {
|
||||
recognition = new Recognition();
|
||||
recognition.continuous = true;
|
||||
recognition.interimResults = false;
|
||||
recognition.onresult = event => {
|
||||
const finalText = Array.from(event.results || [])
|
||||
.filter(result => result.isFinal)
|
||||
.map(result => result[0]?.transcript || '').join(' ').replace(/\s+/g, ' ').trim();
|
||||
if (finalText) {
|
||||
const accumulated = [elements.transcript.value.trim(), finalText]
|
||||
.filter(Boolean).join(' ').replace(/\s+/g, ' ').trim().slice(0, 10255);
|
||||
showReview(accumulated);
|
||||
}
|
||||
};
|
||||
recognition.onerror = event => {
|
||||
elements.start.hidden = false;
|
||||
elements.stop.hidden = true;
|
||||
elements.status.textContent = event.error === 'not-allowed' || event.error === 'service-not-allowed' ?
|
||||
'Microphone permission was denied. Your draft and transcript are unchanged.' :
|
||||
'Voice capture stopped. Your draft and transcript are unchanged.';
|
||||
};
|
||||
recognition.onend = () => {
|
||||
elements.start.hidden = false;
|
||||
elements.stop.hidden = true;
|
||||
};
|
||||
try {
|
||||
recognition.start();
|
||||
} catch (_) {
|
||||
recognition = null;
|
||||
elements.start.hidden = false;
|
||||
elements.stop.hidden = true;
|
||||
elements.status.textContent = 'Voice capture could not start. Your draft and transcript are unchanged.';
|
||||
return;
|
||||
}
|
||||
elements.start.hidden = true;
|
||||
elements.stop.hidden = false;
|
||||
elements.status.textContent = 'Listening… Tap stop when you are finished.';
|
||||
});
|
||||
elements.stop.addEventListener('click', () => {
|
||||
recognition?.stop();
|
||||
elements.status.textContent = 'Finishing transcript…';
|
||||
});
|
||||
|
||||
function clearCheckpoint() {
|
||||
const activeLogin = String(getLogin() || '').trim();
|
||||
if (activeLogin && transcriptStore) void transcriptStore.clear(activeLogin);
|
||||
}
|
||||
|
||||
function commit(mode) {
|
||||
const mapped = mapVoiceTranscript(elements.transcript.value);
|
||||
if (mode === 'replace') {
|
||||
elements.title.value = mapped.title;
|
||||
elements.body.value = mapped.body;
|
||||
} else if (elements.title.value.trim()) {
|
||||
elements.body.value = [elements.body.value.trim(), mapped.title, mapped.body]
|
||||
.filter(Boolean).join('\n\n').slice(0, 10000);
|
||||
} else {
|
||||
elements.title.value = mapped.title;
|
||||
elements.body.value = [elements.body.value.trim(), mapped.body]
|
||||
.filter(Boolean).join('\n\n').slice(0, 10000);
|
||||
}
|
||||
elements.title.dispatchEvent(createEvent('input'));
|
||||
elements.body.dispatchEvent(createEvent('input'));
|
||||
clearCheckpoint();
|
||||
elements.review.hidden = true;
|
||||
elements.status.textContent = 'Transcript added. Review the title and note before saving.';
|
||||
}
|
||||
elements.append.addEventListener('click', () => commit('append'));
|
||||
elements.replace.addEventListener('click', () => commit('replace'));
|
||||
elements.discard?.addEventListener('click', () => {
|
||||
clearCheckpoint();
|
||||
elements.transcript.value = '';
|
||||
elements.review.hidden = true;
|
||||
elements.status.textContent = 'Recovered transcript discarded.';
|
||||
});
|
||||
|
||||
return {supported:true, ready, cancel() { recognition?.abort(); recognition = null; }};
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined') module.exports = {mapVoiceTranscript, createVoiceIssueCapture};
|
||||
@@ -0,0 +1,87 @@
|
||||
(function (root, factory) {
|
||||
const createVoiceTranscriptStore = factory(root.indexedDB);
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createVoiceTranscriptStore;
|
||||
else root.createVoiceTranscriptStore = createVoiceTranscriptStore;
|
||||
})(typeof globalThis !== 'undefined' ? globalThis : this, function buildFactory(defaultIndexedDB) {
|
||||
const dbName = 'stackchain-voice-transcripts-v1';
|
||||
const STORE_NAME = 'checkpoints';
|
||||
const MAX_TRANSCRIPT_LENGTH = 10255;
|
||||
|
||||
function requestResult(request) {
|
||||
return new Promise((resolve, reject) => {
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error || new Error('Private transcript storage failed.'));
|
||||
});
|
||||
}
|
||||
|
||||
function createIndexedDbTransaction(indexedDB) {
|
||||
if (!indexedDB) return null;
|
||||
let databasePromise = null;
|
||||
function openDatabase() {
|
||||
if (databasePromise) return databasePromise;
|
||||
databasePromise = new Promise((resolve, reject) => {
|
||||
const request = indexedDB.open(dbName, 1);
|
||||
request.onupgradeneeded = () => {
|
||||
if (!request.result.objectStoreNames.contains(STORE_NAME)) {
|
||||
request.result.createObjectStore(STORE_NAME, {keyPath:'login'});
|
||||
}
|
||||
};
|
||||
request.onsuccess = () => resolve(request.result);
|
||||
request.onerror = () => reject(request.error || new Error('Private transcript storage is unavailable.'));
|
||||
});
|
||||
return databasePromise;
|
||||
}
|
||||
return async (work, mode = 'readonly') => {
|
||||
const database = await openDatabase();
|
||||
const transaction = database.transaction(STORE_NAME, mode);
|
||||
const store = transaction.objectStore(STORE_NAME);
|
||||
const completed = new Promise((resolve, reject) => {
|
||||
transaction.oncomplete = () => resolve();
|
||||
transaction.onerror = () => reject(transaction.error || new Error('Private transcript storage failed.'));
|
||||
transaction.onabort = () => reject(transaction.error || new Error('Private transcript storage was interrupted.'));
|
||||
});
|
||||
const result = await work({
|
||||
get:key => requestResult(store.get(key)),
|
||||
put:value => requestResult(store.put(value)),
|
||||
delete:key => requestResult(store.delete(key)),
|
||||
});
|
||||
await completed;
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeLogin(value) {
|
||||
return String(value || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeTranscript(value) {
|
||||
return String(value || '').replace(/\s+/g, ' ').trim().slice(0, MAX_TRANSCRIPT_LENGTH);
|
||||
}
|
||||
|
||||
function createVoiceTranscriptStore({transaction = createIndexedDbTransaction(defaultIndexedDB)} = {}) {
|
||||
async function load(login) {
|
||||
const key = normalizeLogin(login);
|
||||
if (!key || !transaction) return '';
|
||||
const record = await transaction(store => store.get(key));
|
||||
return normalizeTranscript(record?.transcript);
|
||||
}
|
||||
|
||||
async function save(login, transcript) {
|
||||
const key = normalizeLogin(login);
|
||||
const value = normalizeTranscript(transcript);
|
||||
if (!key || !value || !transaction) return;
|
||||
await transaction(store => store.put({login:key, transcript:value}), 'readwrite');
|
||||
}
|
||||
|
||||
async function clear(login) {
|
||||
const key = normalizeLogin(login);
|
||||
if (!key || !transaction) return;
|
||||
await transaction(store => store.delete(key), 'readwrite');
|
||||
}
|
||||
|
||||
return {load, save, clear};
|
||||
}
|
||||
|
||||
createVoiceTranscriptStore.databaseName = dbName;
|
||||
return createVoiceTranscriptStore;
|
||||
});
|
||||
@@ -23,7 +23,7 @@ WORKER_RUNTIME_SOURCE = "static/background-issue-sync.js"
|
||||
FEATURE_SOURCES = {
|
||||
"comment-actions": ("static/conversation.js", "static/comment-actions.js"),
|
||||
"issue-capture": (
|
||||
"static/create-issue-sheet.js", "static/update-follow-up.js", "static/shared-image-capture.js",
|
||||
"static/voice-transcript-store.js", "static/voice-issue-capture.js", "static/create-issue-sheet.js", "static/update-follow-up.js", "static/shared-image-capture.js",
|
||||
),
|
||||
"pull-workflow": ("static/pull-sheet.js", "static/review-sheet.js"),
|
||||
"push-notifications": ("static/push-notifications.js",),
|
||||
@@ -36,7 +36,7 @@ FEATURE_SOURCES = {
|
||||
"static/draft-filing-session.js", "static/draft-capacity-dialog.js", "static/work-selection.js",
|
||||
"static/today-work.js", "static/pick-work.js", "static/batch-find-work.js",
|
||||
"static/search-batch-plan.js", "static/issue-evidence-review.js", "static/issue-evidence-editor.js",
|
||||
"static/issue-attachment.js", "static/issue-sheet.js", "static/issue-filing-review.js", "static/issue-filing-receipt.js",
|
||||
"static/issue-attachment.js", "static/checklist-conflict.js", "static/issue-outbox.js", "static/authored-outbox.js", "static/issue-sheet.js", "static/issue-filing-review.js", "static/issue-filing-receipt.js",
|
||||
),
|
||||
}
|
||||
CACHE_DECLARATION = re.compile(
|
||||
|
||||
@@ -2391,6 +2391,16 @@ async def _update_issue_content(
|
||||
):
|
||||
raise IssueNotAvailableError("issue not found")
|
||||
if issue.get("updated_at") != expected_updated_at:
|
||||
if issue.get("title") == title and issue.get("body", "") == body:
|
||||
return {
|
||||
"repository": repository,
|
||||
"number": number,
|
||||
"title": title,
|
||||
"body": body,
|
||||
"state": issue.get("state", "open"),
|
||||
"updated_at": issue.get("updated_at", ""),
|
||||
"url": _safe_web_url(issue.get("html_url")),
|
||||
}
|
||||
raise IssueEditConflictError("issue changed upstream")
|
||||
|
||||
response = await _get_client().patch(
|
||||
|
||||
+1
-1
@@ -1364,7 +1364,7 @@ async def enforce_browser_security_boundary(request: Request, call_next):
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
response.headers["Referrer-Policy"] = "no-referrer"
|
||||
response.headers["Permissions-Policy"] = (
|
||||
"camera=(), microphone=(), geolocation=(), payment=(), usb=()"
|
||||
"camera=(), microphone=(self), geolocation=(), payment=(), usb=()"
|
||||
)
|
||||
response.headers["X-Frame-Options"] = "DENY"
|
||||
if dashboard_auth.mode() == dashboard_auth.OPERATOR_MODE:
|
||||
|
||||
@@ -24,7 +24,7 @@ from fake_gitea import FakeGiteaServer
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TITLE = "Offline artifact journey 863"
|
||||
TITLE = "Offline artifact journey 863."
|
||||
BODY = "Captured on a phone, retained offline, delivered exactly once."
|
||||
ACCESS_TOKEN = "artifact-browser-access-token-863"
|
||||
|
||||
@@ -148,6 +148,14 @@ def test_release_artifact_files_one_mobile_issue_exactly_once_after_offline_relo
|
||||
service_workers="allow",
|
||||
ignore_https_errors=True,
|
||||
)
|
||||
context.add_init_script("""
|
||||
class DeterministicSpeechRecognition {
|
||||
start() { window.__voiceRecognition = this; }
|
||||
stop() { if (this.onend) this.onend(); }
|
||||
abort() { if (this.onend) this.onend(); }
|
||||
}
|
||||
window.SpeechRecognition = DeterministicSpeechRecognition;
|
||||
""")
|
||||
page = context.new_page()
|
||||
page.on("pageerror", lambda error: browser_errors.append(error.stack or str(error)))
|
||||
page.on("console", lambda message: browser_errors.append(message.text) if message.type == "error" else None)
|
||||
@@ -178,8 +186,18 @@ def test_release_artifact_files_one_mobile_issue_exactly_once_after_offline_relo
|
||||
assert page.evaluate("() => navigator.serviceWorker.controller !== null")
|
||||
|
||||
new_action.click()
|
||||
page.locator("#create-issue-title").fill(TITLE)
|
||||
page.locator("#create-issue-body").fill(BODY)
|
||||
expect(page.locator("#voice-issue-capture")).to_be_visible()
|
||||
page.locator("#start-voice-issue-capture").click()
|
||||
page.evaluate("""([title, body]) => {
|
||||
const result = [{ transcript: title + ' ' + body }];
|
||||
result.isFinal = true;
|
||||
window.__voiceRecognition.onresult({ results: [result] });
|
||||
}""", [TITLE, BODY])
|
||||
expect(page.locator("#voice-issue-review")).to_be_visible()
|
||||
expect(page.locator("#append-voice-issue-transcript")).to_have_text("Use transcript")
|
||||
page.locator("#append-voice-issue-transcript").click()
|
||||
expect(page.locator("#create-issue-title")).to_have_value(TITLE)
|
||||
expect(page.locator("#create-issue-body")).to_have_value(BODY)
|
||||
page.locator("#file-new-issue").click()
|
||||
expect(page.locator("#create-issue-filing")).to_be_visible()
|
||||
page.locator("#create-issue-repository").select_option("acme/mobile")
|
||||
|
||||
@@ -77,6 +77,171 @@ outbox.flush('timmy').then(result => process.stdout.write(JSON.stringify({{persi
|
||||
assert output["remaining"] == []
|
||||
|
||||
|
||||
def test_authored_outbox_persists_and_delivers_revision_checked_issue_content():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values = new Map(); const calls = [];
|
||||
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v),removeItem:k=>values.delete(k)}};
|
||||
const outbox = createAuthoredOutbox({{
|
||||
storage, getOwnerLogin:()=> 'timmy',
|
||||
fetchJson: async (url, options) => {{
|
||||
calls.push({{url,method:options.method,key:options.headers['Idempotency-Key'],body:JSON.parse(options.body)}});
|
||||
return {{repository:'stackchain/dashboard',number:17,title:'Ship',body:'- [x] Test',updated_at:'2026-08-15T11:00:00Z'}};
|
||||
}},
|
||||
}});
|
||||
const queued = outbox.enqueue({{
|
||||
kind:'issue-content',repository:'stackchain/dashboard',number:17,operationId:'check-op',
|
||||
title:'Ship',body:'- [x] Test',expectedUpdatedAt:'2026-08-15T10:00:00Z',
|
||||
}});
|
||||
const restored = createAuthoredOutbox({{storage}}).list()[0];
|
||||
outbox.flush('timmy').then(result => process.stdout.write(JSON.stringify({{queued,restored,calls,result,remaining:outbox.list()}})));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["queued"]["expectedUpdatedAt"] == "2026-08-15T10:00:00Z"
|
||||
assert output["restored"]["title"] == "Ship"
|
||||
assert output["calls"] == [{
|
||||
"url": "api/v1/repos/stackchain/dashboard/issues/17/content",
|
||||
"method": "PATCH",
|
||||
"key": "check-op",
|
||||
"body": {
|
||||
"title": "Ship", "body": "- [x] Test",
|
||||
"expected_updated_at": "2026-08-15T10:00:00Z",
|
||||
},
|
||||
}]
|
||||
assert output["result"]["confirmed"][0]["body"] == "- [x] Test"
|
||||
assert output["remaining"] == []
|
||||
|
||||
|
||||
def test_durable_issue_content_admission_coalesces_latest_body_on_original_revision():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values = new Map(); const mirrors = []; const ids = ['check-1', 'check-2'];
|
||||
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const outbox = createAuthoredOutbox({{
|
||||
storage, getOwnerLogin:()=> 'timmy', createOperationId:()=>ids.shift(),
|
||||
backgroundSync:{{
|
||||
reconcile:async items=>mirrors.push(items.map(item=>({{...item}}))),
|
||||
requestSync:async()=>{{}},
|
||||
}},
|
||||
}});
|
||||
(async()=>{{
|
||||
await outbox.enqueueDurably({{kind:'issue-content',repository:'stackchain/dashboard',number:17,
|
||||
title:'Ship',body:'- [x] Build\\n- [ ] Test',expectedUpdatedAt:'server-revision'}});
|
||||
const second = await outbox.enqueueDurably({{kind:'issue-content',repository:'stackchain/dashboard',number:17,
|
||||
title:'Ship',body:'- [x] Build\\n- [x] Test',expectedUpdatedAt:'pending-local-revision'}});
|
||||
process.stdout.write(JSON.stringify({{items:outbox.list(),second,mirrors}}));
|
||||
}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert len(output["items"]) == 1
|
||||
assert output["items"][0]["id"] == "check-1"
|
||||
assert output["items"][0]["operationId"] == "check-2"
|
||||
assert output["items"][0]["body"] == "- [x] Build\n- [x] Test"
|
||||
assert output["items"][0]["expectedUpdatedAt"] == "server-revision"
|
||||
assert output["second"]["item"] == output["items"][0]
|
||||
assert len(output["mirrors"][1]) == 1
|
||||
assert output["mirrors"][1][0]["operationId"] == "check-2"
|
||||
|
||||
|
||||
def test_durable_issue_content_coalesces_ordered_checklist_management_intent():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values = new Map(); const ids = ['manage-1','manage-2'];
|
||||
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const outbox = createAuthoredOutbox({{
|
||||
storage,getOwnerLogin:()=> 'timmy',createOperationId:()=>ids.shift(),
|
||||
backgroundSync:{{reconcile:async()=>{{}},requestSync:async()=>{{}}}},
|
||||
}});
|
||||
(async()=>{{
|
||||
await outbox.enqueueDurably({{kind:'issue-content',repository:'o/r',number:9,title:'Ship',
|
||||
baseBody:'- [ ] Build\\n- [ ] Test',body:'- [ ] Compile\\n- [ ] Test',expectedUpdatedAt:'old',
|
||||
checklistOperation:{{action:'rename',index:0,label:'Compile'}}}});
|
||||
await outbox.enqueueDurably({{kind:'issue-content',repository:'o/r',number:9,title:'Ship',
|
||||
baseBody:'- [ ] Compile\\n- [ ] Test',body:'- [ ] Test\\n- [ ] Compile',expectedUpdatedAt:'old',
|
||||
checklistOperation:{{action:'move-later',index:0}}}});
|
||||
process.stdout.write(JSON.stringify(outbox.list()[0]));
|
||||
}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["baseBody"] == "- [ ] Build\n- [ ] Test"
|
||||
assert output["body"] == "- [ ] Test\n- [ ] Compile"
|
||||
assert output["checklistOperations"] == [
|
||||
{"action": "rename", "index": 0, "label": "Compile"},
|
||||
{"action": "move-later", "index": 0},
|
||||
]
|
||||
|
||||
|
||||
def test_failed_durable_issue_content_replacement_restores_previous_intent():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values = new Map(); const ids = ['check-1', 'check-2']; let admissions = 0;
|
||||
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const outbox = createAuthoredOutbox({{
|
||||
storage, getOwnerLogin:()=> 'timmy', createOperationId:()=>ids.shift(),
|
||||
backgroundSync:{{
|
||||
reconcile:async()=>{{if (++admissions === 2) throw new Error('IndexedDB unavailable');}},
|
||||
requestSync:async()=>{{}},
|
||||
}},
|
||||
}});
|
||||
(async()=>{{
|
||||
await outbox.enqueueDurably({{kind:'issue-content',repository:'o/r',number:9,
|
||||
title:'Ship',body:'- [x] Build\\n- [ ] Test',expectedUpdatedAt:'server-revision'}});
|
||||
let error = '';
|
||||
try {{
|
||||
await outbox.enqueueDurably({{kind:'issue-content',repository:'o/r',number:9,
|
||||
title:'Ship',body:'- [x] Build\\n- [x] Test',expectedUpdatedAt:'server-revision'}});
|
||||
}} catch (caught) {{ error = caught.message; }}
|
||||
process.stdout.write(JSON.stringify({{error,items:outbox.list()}}));
|
||||
}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["error"] == "IndexedDB unavailable"
|
||||
assert len(output["items"]) == 1
|
||||
assert output["items"][0]["operationId"] == "check-1"
|
||||
assert output["items"][0]["body"] == "- [x] Build\n- [ ] Test"
|
||||
|
||||
|
||||
def test_issue_content_conflict_resolution_rebases_task_delta_and_mirrors_before_retry():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const mergeChecklistConflict = require({json.dumps(str(Path(__file__).parents[1] / 'frontend' / 'checklist-conflict.js'))});
|
||||
const initial = {{version:2,items:[{{
|
||||
id:'check-1',operationId:'old-op',kind:'issue-content',ownerLogin:'timmy',status:'attention',
|
||||
repository:'o/r',number:9,title:'Ship',baseBody:'Intro\\n- [ ] Build\\n- [ ] Test',
|
||||
body:'Intro\\n- [x] Build\\n- [ ] Test',expectedUpdatedAt:'old-revision',error:'Issue changed',
|
||||
}}]}};
|
||||
const values = new Map([['stackchain.authored-outbox.v1', JSON.stringify(initial)]]);
|
||||
const mirrors = []; let syncs = 0;
|
||||
const storage = {{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const outbox = createAuthoredOutbox({{
|
||||
storage, getOwnerLogin:()=> 'timmy', createOperationId:()=> 'rebased-op', mergeChecklistConflict,
|
||||
backgroundSync:{{reconcile:async items=>mirrors.push(items.map(item=>({{...item}}))),requestSync:async()=>{{syncs += 1;}}}},
|
||||
}});
|
||||
(async()=>{{
|
||||
const result = await outbox.resolveIssueContentConflict('check-1', {{
|
||||
title:'Ship safely', body:'Remote intro\\n- [ ] Test\\n- [ ] Build', updated_at:'latest-revision',
|
||||
}}, 'timmy');
|
||||
process.stdout.write(JSON.stringify({{result,item:outbox.list()[0],mirrors,syncs}}));
|
||||
}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["result"]["changes"] == [{"label": "Build", "checked": True}]
|
||||
assert output["item"]["status"] == "queued"
|
||||
assert output["item"]["operationId"] == "rebased-op"
|
||||
assert output["item"]["title"] == "Ship safely"
|
||||
assert output["item"]["body"] == "Remote intro\n- [ ] Test\n- [x] Build"
|
||||
assert output["item"]["baseBody"] == "Remote intro\n- [ ] Test\n- [ ] Build"
|
||||
assert output["item"]["expectedUpdatedAt"] == "latest-revision"
|
||||
assert "error" not in output["item"]
|
||||
assert output["mirrors"][-1][0] == output["item"]
|
||||
assert output["syncs"] == 1
|
||||
|
||||
|
||||
def test_authored_outbox_persists_and_delivers_desired_blocker_state():
|
||||
script = f"""
|
||||
const createAuthoredOutbox = require({json.dumps(str(OUTBOX))});
|
||||
|
||||
@@ -96,6 +96,69 @@ const fetchJson=async url=>url==='api/v1/background-identity'?{{login:'timmy'}}:
|
||||
}
|
||||
|
||||
|
||||
def test_closed_app_sync_delivers_revision_checked_issue_content():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
let item = {{
|
||||
id:'check-1',operationId:'check-1',kind:'issue-content',ownerLogin:'timmy',status:'queued',
|
||||
repository:'stackchain/dashboard',number:17,title:'Ship',body:'- [x] Test',expectedUpdatedAt:'2026-08-15T10:00:00Z',
|
||||
}};
|
||||
const state={{calls:[],completed:[]}};
|
||||
const store={{
|
||||
claimNext:async()=>item?{{...item}}:null,
|
||||
complete:async id=>{{state.completed.push(id);item=null;}},
|
||||
release:async()=>{{}},fail:async()=>{{}},countBlocked:async()=>0,
|
||||
}};
|
||||
const fetchJson=async(url,options={{}})=>{{
|
||||
state.calls.push({{url,method:options.method,key:options.headers?.['Idempotency-Key']||'',body:options.body?JSON.parse(options.body):null}});
|
||||
if(url==='api/v1/background-identity') return {{login:'timmy'}};
|
||||
return {{repository:'stackchain/dashboard',number:17,title:'Ship',body:'- [x] Test',updated_at:'2026-08-15T11:00:00Z'}};
|
||||
}};
|
||||
(async()=>{{const result=await createBackgroundIssueSync({{store,fetchJson}}).flush();process.stdout.write(JSON.stringify({{state,result}}));}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["state"]["calls"][1] == {
|
||||
"url": "api/v1/repos/stackchain/dashboard/issues/17/content",
|
||||
"method": "PATCH",
|
||||
"key": "check-1",
|
||||
"body": {
|
||||
"title": "Ship", "body": "- [x] Test",
|
||||
"expected_updated_at": "2026-08-15T10:00:00Z",
|
||||
},
|
||||
}
|
||||
assert output["state"]["completed"] == ["check-1"]
|
||||
assert output["result"]["confirmed"][0]["body"] == "- [x] Test"
|
||||
|
||||
|
||||
def test_active_issue_content_delivery_rejects_a_false_durable_replacement():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
const records = new Map([['check-1', {{
|
||||
id:'check-1',operationId:'old-op',kind:'issue-content',outboxLane:'authored',
|
||||
ownerLogin:'timmy',status:'sending',claimUntil:200,body:'- [x] Build\\n- [ ] Test'
|
||||
}}]]); let tail=Promise.resolve();
|
||||
const transaction=work=>{{const run=tail.then(()=>work({{
|
||||
getAll:async()=>[...records.values()].map(value=>({{...value}})),
|
||||
put:async value=>records.set(value.id,{{...value}}),delete:async id=>records.delete(id),
|
||||
}}));tail=run.catch(()=>{{}});return run;}};
|
||||
(async()=>{{
|
||||
const store=createBackgroundIssueSync.createIssueSyncStore({{transaction,now:()=>100}});
|
||||
let error='';
|
||||
try {{ await store.reconcile([{{
|
||||
id:'check-1',operationId:'new-op',kind:'issue-content',ownerLogin:'timmy',status:'queued',
|
||||
body:'- [x] Build\\n- [x] Test'
|
||||
}}], 'authored'); }} catch (caught) {{ error=caught.message; }}
|
||||
process.stdout.write(JSON.stringify({{error,snapshot:await store.snapshot()}}));
|
||||
}})();
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["error"] == "Checklist sync is already delivering. Retry this change."
|
||||
assert output["snapshot"][0]["operationId"] == "old-op"
|
||||
assert output["snapshot"][0]["body"] == "- [x] Build\n- [ ] Test"
|
||||
|
||||
|
||||
def test_closed_app_sync_delivers_desired_blocker_state():
|
||||
script = f"""
|
||||
const createBackgroundIssueSync = require({json.dumps(str(SYNC))});
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MERGER = Path(__file__).parents[1] / "frontend" / "checklist-conflict.js"
|
||||
|
||||
|
||||
def run_node(script: str):
|
||||
result = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def test_merge_applies_local_task_delta_to_latest_body_without_reverting_remote_edits():
|
||||
script = f"""
|
||||
const mergeChecklistConflict = require({json.dumps(str(MERGER))});
|
||||
const result = mergeChecklistConflict({{
|
||||
baseBody:'Intro\\n- [ ] Build\\n- [ ] Test',
|
||||
localBody:'Intro\\n- [x] Build\\n- [ ] Test',
|
||||
remoteBody:'Updated intro\\n- [ ] Test\\n- [ ] Build\\n- [x] Document',
|
||||
}});
|
||||
process.stdout.write(JSON.stringify(result));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output == {
|
||||
"body": "Updated intro\n- [ ] Test\n- [x] Build\n- [x] Document",
|
||||
"changes": [{"label": "Build", "checked": True}],
|
||||
"conflicts": [],
|
||||
}
|
||||
|
||||
|
||||
def test_merge_reports_missing_or_ambiguous_changed_tasks_without_writing_a_body():
|
||||
script = f"""
|
||||
const mergeChecklistConflict = require({json.dumps(str(MERGER))});
|
||||
const missing = mergeChecklistConflict({{
|
||||
baseBody:'- [ ] Ship', localBody:'- [x] Ship', remoteBody:'- [ ] Release',
|
||||
}});
|
||||
const duplicate = mergeChecklistConflict({{
|
||||
baseBody:'- [ ] Ship', localBody:'- [x] Ship', remoteBody:'- [ ] Ship\\n- [ ] Ship',
|
||||
}});
|
||||
process.stdout.write(JSON.stringify({{missing,duplicate}}));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["missing"]["body"] is None
|
||||
assert output["missing"]["conflicts"] == [{"label": "Ship", "reason": "missing"}]
|
||||
assert output["duplicate"]["body"] is None
|
||||
assert output["duplicate"]["conflicts"] == [{"label": "Ship", "reason": "ambiguous"}]
|
||||
|
||||
|
||||
def test_merge_appends_a_locally_added_step_to_remote_edits_without_reverting_them():
|
||||
script = f"""
|
||||
const mergeChecklistConflict = require({json.dumps(str(MERGER))});
|
||||
const result = mergeChecklistConflict({{
|
||||
baseBody:'Intro\\n- [ ] Build',
|
||||
localBody:'Intro\\n- [ ] Build\\n- [ ] Verify rollback',
|
||||
remoteBody:'Updated intro\\n- [x] Build\\n- [ ] Notify support',
|
||||
}});
|
||||
process.stdout.write(JSON.stringify(result));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output == {
|
||||
"body": "Updated intro\n- [x] Build\n- [ ] Notify support\n- [ ] Verify rollback",
|
||||
"changes": [{"label": "Verify rollback", "checked": False, "added": True}],
|
||||
"conflicts": [],
|
||||
}
|
||||
|
||||
|
||||
def test_merge_rejects_an_ambiguous_locally_added_duplicate():
|
||||
script = f"""
|
||||
const mergeChecklistConflict = require({json.dumps(str(MERGER))});
|
||||
const result = mergeChecklistConflict({{
|
||||
baseBody:'- [ ] Build',
|
||||
localBody:'- [ ] Build\\n- [ ] Verify rollback\\n- [ ] verify rollback ',
|
||||
remoteBody:'- [x] Build',
|
||||
}});
|
||||
process.stdout.write(JSON.stringify(result));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["body"] is None
|
||||
assert output["conflicts"] == [{"label": "Verify rollback", "reason": "ambiguous"}]
|
||||
|
||||
|
||||
def test_merge_replays_rename_and_reorder_intent_onto_unrelated_remote_edits():
|
||||
script = f"""
|
||||
const mergeChecklistConflict = require({json.dumps(str(MERGER))});
|
||||
const result = mergeChecklistConflict({{
|
||||
baseBody:'Intro\\n- [ ] Build\\n- [ ] Test',
|
||||
localBody:'Intro\\n- [ ] Test\\n- [ ] Compile',
|
||||
remoteBody:'Updated intro\\n- [x] Build\\n- [ ] Test\\nRemote note',
|
||||
operations:[
|
||||
{{action:'rename',index:0,label:'Compile'}},
|
||||
{{action:'move-later',index:0}},
|
||||
],
|
||||
}});
|
||||
process.stdout.write(JSON.stringify(result));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output == {
|
||||
"body": "Updated intro\n- [ ] Test\n- [x] Compile\nRemote note",
|
||||
"changes": [
|
||||
{"label": "Build", "renamed": "Compile"},
|
||||
{"label": "Compile", "moved": "later"},
|
||||
],
|
||||
"conflicts": [],
|
||||
}
|
||||
@@ -303,4 +303,4 @@ async def test_unread_update_offers_reply_mark_read_and_next_independent_of_toda
|
||||
assert '.update-reply-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr));' in html
|
||||
assert '.update-reply-actions button { min-height:44px;' in html
|
||||
worker = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
assert "stackchain-dashboard-shell-v107" in worker
|
||||
assert "stackchain-dashboard-shell-v108" in worker
|
||||
@@ -349,7 +349,7 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["deletedAtIdle"] == []
|
||||
assert result["deletedDatabases"] == [
|
||||
"stackchain-background-outbox-v1", "stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-unfiled-captures-v1", "stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["remaining"] == ["gitea.preference"]
|
||||
assert result["replaced"] == [
|
||||
@@ -375,7 +375,7 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["remaining"] == ["gitea.preference"]
|
||||
assert result["deletedDatabases"] == [
|
||||
"stackchain-background-outbox-v1", "stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-unfiled-captures-v1", "stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["deletedCaches"] == ["stackchain-dashboard-shell-v15"]
|
||||
assert result["replaced"] == ["/dashboard/login?reason=session-expired"]
|
||||
@@ -506,7 +506,7 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["remaining"] == ["gitea.preference"]
|
||||
assert result["deletedDatabases"] == [
|
||||
"stackchain-background-outbox-v1", "stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-unfiled-captures-v1", "stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["deletedCaches"] == ["stackchain-dashboard-shell-v15"]
|
||||
assert result["workerMessages"] == [{"type": "stackchain-purge-outbox"}]
|
||||
@@ -529,7 +529,7 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["remaining"] == ["gitea.preference"]
|
||||
assert result["deletedDatabases"] == [
|
||||
"stackchain-background-outbox-v1", "stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-unfiled-captures-v1", "stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["deletedCaches"] == ["stackchain-dashboard-shell-v15"]
|
||||
assert result["workerMessages"] == [{"type": "stackchain-purge-outbox"}]
|
||||
@@ -625,7 +625,7 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["remaining"] == ["gitea.preference"]
|
||||
assert result["deletedDatabases"] == [
|
||||
"stackchain-background-outbox-v1", "stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-unfiled-captures-v1", "stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["deletedCaches"] == ["stackchain-dashboard-shell-v15"]
|
||||
assert result["assigned"] == "/dashboard/login"
|
||||
@@ -809,6 +809,28 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["workerMessages"] == [{"type": "stackchain-resume-outbox"}]
|
||||
|
||||
|
||||
def test_reconnect_requests_queued_delivery_resume_after_offline_reload():
|
||||
result = run_session_scenario(
|
||||
"""
|
||||
boundary.startReconnectResume();
|
||||
state.responsePayload = {authenticated:true, expires_at:200000, idle_expires_at:150000};
|
||||
await state.activityListeners.online();
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["requests"][0]["url"] == "/dashboard/api/v1/session"
|
||||
assert result["workerMessages"] == [
|
||||
{
|
||||
"type": "stackchain-session-lease",
|
||||
"expiresAt": 200000,
|
||||
"idleExpiresAt": 150000,
|
||||
},
|
||||
{"type": "stackchain-resume-outbox"},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_loads_session_boundary_first_and_offers_sign_out():
|
||||
html = await dashboard()
|
||||
|
||||
@@ -121,6 +121,28 @@ process.stdout.write(JSON.stringify(drafts));
|
||||
assert output[1]["label"] == "Queued issue"
|
||||
|
||||
|
||||
def test_draft_inbox_identifies_account_bound_checklist_conflicts_for_review():
|
||||
script = f"""
|
||||
const createDraftInbox = require({json.dumps(str(DRAFTS))});
|
||||
const record = {{version:2,items:[{{
|
||||
id:'check-1',kind:'issue-content',ownerLogin:'timmy',status:'attention',repository:'o/r',number:7,
|
||||
title:'Ship',baseBody:'- [ ] Build',body:'- [x] Build',expectedUpdatedAt:'old',error:'Issue changed',queuedAt:12,
|
||||
}}]}};
|
||||
const values = new Map([['stackchain.authored-outbox.v1', JSON.stringify(record)]]);
|
||||
const storage = {{get length(){{return values.size}},key:i=>Array.from(values.keys())[i]||null,getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
|
||||
const owned = createDraftInbox({{storage,getCurrentLogin:()=>'timmy'}}).list()[0];
|
||||
const other = createDraftInbox({{storage,getCurrentLogin:()=>'alexander'}}).list()[0];
|
||||
process.stdout.write(JSON.stringify({{owned,other}}));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["owned"]["label"] == "Checklist conflict"
|
||||
assert output["owned"]["checklist_conflict"] is True
|
||||
assert output["owned"]["quarantined"] is False
|
||||
assert output["other"]["checklist_conflict"] is False
|
||||
assert output["other"]["quarantined"] is True
|
||||
|
||||
|
||||
def test_draft_inbox_exposes_queued_review_with_review_route_and_actionable_state():
|
||||
script = f"""
|
||||
const createDraftInbox = require({json.dumps(str(DRAFTS))});
|
||||
|
||||
@@ -234,7 +234,7 @@ async def test_streaming_reads_share_the_same_bounded_read_capacity():
|
||||
try:
|
||||
await asyncio.wait_for(saturated.wait(), timeout=0.2)
|
||||
with pytest.raises(gitea_proxy.GiteaOverloadedError):
|
||||
await asyncio.wait_for(gitea_proxy.fetch("third"), timeout=0.1)
|
||||
await asyncio.wait_for(gitea_proxy.fetch("third"), timeout=1.0)
|
||||
finally:
|
||||
release.set()
|
||||
await asyncio.gather(*streams)
|
||||
|
||||
@@ -664,6 +664,45 @@ async def test_gitea_edit_issue_rejects_stale_revision_without_patch():
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_edit_issue_confirms_already_applied_content_after_lost_response():
|
||||
requests = []
|
||||
|
||||
async def handler(request):
|
||||
requests.append(request)
|
||||
if request.url.path == "/api/v1/user":
|
||||
return httpx.Response(200, json={"login": "timmy"})
|
||||
return httpx.Response(200, json={
|
||||
"number": 17,
|
||||
"title": "My draft",
|
||||
"body": "Draft body",
|
||||
"state": "open",
|
||||
"updated_at": "2026-08-07T10:02:00Z",
|
||||
"assignees": [{"login": "timmy"}],
|
||||
"pull_request": None,
|
||||
"html_url": "https://forge.example/stackchain/api/issues/17",
|
||||
})
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
result = await gitea_proxy.update_assigned_issue(
|
||||
"stackchain/api", 17, "My draft", "Draft body",
|
||||
"2026-08-07T10:00:00Z",
|
||||
)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert [(request.method, request.url.path) for request in requests] == [
|
||||
("GET", "/api/v1/user"),
|
||||
("GET", "/api/v1/repos/stackchain/api/issues/17"),
|
||||
]
|
||||
assert result == {
|
||||
"repository": "stackchain/api", "number": 17, "title": "My draft",
|
||||
"body": "Draft body", "state": "open", "updated_at": "2026-08-07T10:02:00Z",
|
||||
"url": "https://forge.example/stackchain/api/issues/17",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_edit_issue_revalidates_assignment_and_confirms_content():
|
||||
requests = []
|
||||
|
||||
@@ -72,6 +72,40 @@ outbox.flush('timmy').then(result=>process.stdout.write(JSON.stringify({{result,
|
||||
assert "relatedDraft" not in output["sentBody"]
|
||||
|
||||
|
||||
def test_confirmed_delivery_returns_durable_checklist_promotion_without_sending_parent_context():
|
||||
script = f"""
|
||||
const createIssueOutbox = require({json.dumps(str(OUTBOX))});
|
||||
const values=new Map(); let sentBody;
|
||||
const storage={{getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)}};
|
||||
const outbox=createIssueOutbox({{
|
||||
storage,getOwnerLogin:()=> 'timmy',createOperationId:()=> 'promote-operation',
|
||||
fetchJson:async (_url,options)=>{{sentBody=JSON.parse(options.body);return {{repository:'stackchain/dashboard',number:44,title:'Build',url:'https://forge.example/issues/44'}};}},
|
||||
}});
|
||||
outbox.enqueue({{
|
||||
repository:'stackchain/dashboard',title:'Build',body:'Related parent',
|
||||
relatedDraft:{{repository:'stackchain/dashboard',title:'',body:'',labelIds:[],
|
||||
checklistPromotion:{{repository:'stackchain/dashboard',number:17,url:'https://forge.example/issues/17',
|
||||
title:'Parent',body:'- [ ] Build',updatedAt:'old',taskIndex:0}}}},
|
||||
}});
|
||||
outbox.flush('timmy').then(result=>process.stdout.write(JSON.stringify({{result,sentBody}})));
|
||||
"""
|
||||
output = run_node(script)
|
||||
|
||||
assert output["result"]["filings"] == [{
|
||||
"issue": {"repository": "stackchain/dashboard", "number": 44,
|
||||
"title": "Build", "url": "https://forge.example/issues/44"},
|
||||
"relatedDraft": {
|
||||
"repository": "stackchain/dashboard", "title": "", "body": "", "labelIds": [],
|
||||
"checklistPromotion": {
|
||||
"repository": "stackchain/dashboard", "number": 17,
|
||||
"url": "https://forge.example/issues/17", "title": "Parent",
|
||||
"body": "- [ ] Build", "updatedAt": "old", "taskIndex": 0,
|
||||
},
|
||||
},
|
||||
}]
|
||||
assert "checklistPromotion" not in output["sentBody"]
|
||||
|
||||
|
||||
def test_editing_a_queued_issue_refreshes_its_related_plan():
|
||||
script = f"""
|
||||
const createIssueOutbox = require({json.dumps(str(OUTBOX))});
|
||||
|
||||
@@ -347,5 +347,5 @@ async def test_dashboard_syncs_every_later_change_and_exposes_account_status():
|
||||
def test_later_sync_ships_atomically_in_the_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/later-sync.js'" in source
|
||||
@@ -40,6 +40,22 @@ def toggle_task(payload, task_index, checked):
|
||||
)
|
||||
|
||||
|
||||
def manage_task(payload, task_index, operation):
|
||||
script = (
|
||||
f"const manage = require({json.dumps(str(FRONTEND / 'issue-sheet.js'))}).manageChecklistTask;"
|
||||
f"process.stdout.write(JSON.stringify(manage({json.dumps(payload)}, "
|
||||
f"{task_index}, {json.dumps(operation)})));"
|
||||
)
|
||||
return json.loads(
|
||||
subprocess.run(
|
||||
["node", "-e", script],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
).stdout
|
||||
)
|
||||
|
||||
|
||||
class ScriptSourceParser(HTMLParser):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
@@ -114,6 +130,19 @@ def test_interactive_markdown_tasks_expose_accessible_source_indices():
|
||||
)
|
||||
|
||||
|
||||
def test_manageable_markdown_tasks_expose_touch_action_with_position_boundaries():
|
||||
rendered = render_markdown(
|
||||
"- [ ] Verify production\n- [x] Notify support",
|
||||
{"interactiveTasks": True, "manageTasks": True},
|
||||
)
|
||||
|
||||
assert 'class="task-list-manage" data-task-index="0"' in rendered
|
||||
assert 'aria-label="Manage step: Verify production"' in rendered
|
||||
assert 'data-task-first="true"' in rendered
|
||||
assert 'class="task-list-manage" data-task-index="1"' in rendered
|
||||
assert 'data-task-last="true"' in rendered
|
||||
|
||||
|
||||
def test_interactive_task_toggle_changes_exact_source_marker_only():
|
||||
body = (
|
||||
"```md\r\n- [ ] example only\r\n```\r\n"
|
||||
@@ -126,6 +155,51 @@ def test_interactive_task_toggle_changes_exact_source_marker_only():
|
||||
)
|
||||
|
||||
|
||||
def test_manage_task_renames_exact_visible_task_and_preserves_nested_step_line_endings_and_fences():
|
||||
body = (
|
||||
"```md\r\n- [ ] example only\r\n```\r\n"
|
||||
"- [ ] Build\r\n - [X] Verify rollback\r\n- [ ] Release\r\n"
|
||||
)
|
||||
|
||||
assert manage_task(body, 1, {"action": "rename", "label": "Ship"}) == (
|
||||
"```md\r\n- [ ] example only\r\n```\r\n"
|
||||
"- [ ] Build\r\n - [X] Verify rollback\r\n- [ ] Ship\r\n"
|
||||
)
|
||||
|
||||
|
||||
def test_manage_task_removes_only_the_selected_task_line():
|
||||
body = "Plan\n- [ ] Build\n- [x] Test\n\nNotes"
|
||||
|
||||
assert manage_task(body, 0, {"action": "remove"}) == "Plan\n- [x] Test\n\nNotes"
|
||||
|
||||
|
||||
def test_manage_task_moves_a_step_within_its_list_without_changing_step_content():
|
||||
body = "Plan\n- [ ] Build\n- [x] Test\n- [ ] Release\n\nNotes"
|
||||
|
||||
assert manage_task(body, 2, {"action": "move-earlier"}) == (
|
||||
"Plan\n- [ ] Build\n- [ ] Release\n- [x] Test\n\nNotes"
|
||||
)
|
||||
assert manage_task(body, 0, {"action": "move-later"}) == (
|
||||
"Plan\n- [x] Test\n- [ ] Build\n- [ ] Release\n\nNotes"
|
||||
)
|
||||
|
||||
|
||||
def test_manage_task_rejects_an_empty_or_duplicate_renamed_label():
|
||||
script = f"""
|
||||
const manage = require({json.dumps(str(FRONTEND / 'issue-sheet.js'))}).manageChecklistTask;
|
||||
const body = '- [ ] Build\\n- [x] Test';
|
||||
const errors = ['', ' test '].map(label => {{
|
||||
try {{ manage(body, 0, {{action:'rename',label}}); return null; }}
|
||||
catch (error) {{ return error.message; }}
|
||||
}});
|
||||
process.stdout.write(JSON.stringify(errors));
|
||||
"""
|
||||
|
||||
assert json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout) == ["Enter a checklist step.", "That checklist step already exists."]
|
||||
|
||||
|
||||
def test_markdown_renderer_allows_only_safe_links_and_keeps_html_inert():
|
||||
rendered = render_markdown(
|
||||
"[Forge](https://forge.example/work?q=1&safe=yes) "
|
||||
@@ -155,7 +229,7 @@ def test_all_read_only_work_bodies_use_the_shared_markdown_renderer():
|
||||
"renderMarkdown(detail.body || 'No description provided.')",
|
||||
"renderMarkdown(item.body || 'No description provided.')",
|
||||
"renderMarkdown(review.body)",
|
||||
"issueController.renderTasks(qs('#issue-sheet-body'), detail, !selectedIssueOffline",
|
||||
"issueController.renderTasks(qs('#issue-sheet-body'), detail,",
|
||||
)
|
||||
for path in expected_paths:
|
||||
assert path in dashboard
|
||||
@@ -182,4 +256,4 @@ def test_markdown_work_bodies_are_mobile_safe_block_containers():
|
||||
assert ".markdown-content { min-width:0; max-width:100%; overflow-wrap:anywhere;" in css
|
||||
assert ".markdown-content pre { max-width:100%; overflow-x:auto;" in css
|
||||
assert ".markdown-content a { min-height:44px;" in css
|
||||
assert "stackchain-dashboard-shell-v107" in worker
|
||||
assert "stackchain-dashboard-shell-v108" in worker
|
||||
@@ -45,7 +45,7 @@ def test_offline_shell_contains_every_local_dashboard_runtime_asset():
|
||||
shell_assets = set(re.findall(r"BASE \+ '([^']+)'", worker.split("async function sessionCsrf", 1)[0]))
|
||||
|
||||
assert local_assets <= shell_assets, f"Offline shell is missing: {sorted(local_assets - shell_assets)}"
|
||||
assert "stackchain-dashboard-shell-v107" in worker
|
||||
assert "stackchain-dashboard-shell-v108" in worker
|
||||
|
||||
|
||||
def test_all_conversation_composers_offer_accessible_mobile_mentions():
|
||||
|
||||
@@ -214,7 +214,7 @@ def test_mobile_dashboard_mounts_phone_safe_device_setup_flow():
|
||||
assert "promptStorage:localStorage" in dashboard
|
||||
assert "pushControllerReady.then(ensureDeviceSetup)" in dashboard
|
||||
assert "BASE + 'static/mobile-device-setup.js'" in worker
|
||||
assert "stackchain-dashboard-shell-v107" in worker
|
||||
assert "stackchain-dashboard-shell-v108" in worker
|
||||
assert ".device-setup-panel" in css
|
||||
assert ".device-readiness-card" in css
|
||||
assert "overflow-x:hidden" in css
|
||||
|
||||
@@ -283,4 +283,4 @@ async def test_dashboard_wires_thumb_safe_start_day_briefing_into_offline_mobile
|
||||
assert ".mobile-start-day-finish { min-height:44px;" in html
|
||||
assert "max-width:100%; overflow-wrap:anywhere;" in html
|
||||
assert "BASE + 'static/mobile-start-day.js'" in service_worker
|
||||
assert "stackchain-dashboard-shell-v107" in service_worker
|
||||
assert "stackchain-dashboard-shell-v108" in service_worker
|
||||
+569
-3
@@ -33,6 +33,7 @@ LATER_PICKER = Path(__file__).parents[1] / "frontend" / "later-picker.js"
|
||||
LATER_AND_START = Path(__file__).parents[1] / "frontend" / "later-and-start.js"
|
||||
REVIEW_SHEET = Path(__file__).parents[1] / "frontend" / "review-sheet.js"
|
||||
ISSUE_SHEET = Path(__file__).parents[1] / "frontend" / "issue-sheet.js"
|
||||
FRONTEND_BUNDLE = Path(__file__).parents[1] / "src" / "frontend_bundle.py"
|
||||
CREATE_ISSUE_SHEET = Path(__file__).parents[1] / "frontend" / "create-issue-sheet.js"
|
||||
PULL_SHEET = Path(__file__).parents[1] / "frontend" / "pull-sheet.js"
|
||||
CONVERSATION = Path(__file__).parents[1] / "frontend" / "conversation.js"
|
||||
@@ -99,6 +100,144 @@ process.stdout.write(JSON.stringify(buildMyWork({json.dumps(payload)})));
|
||||
assert result[1]["reason"] == "Filed by you"
|
||||
|
||||
|
||||
def test_completed_child_resolves_only_a_canonical_reciprocal_parent_task():
|
||||
script = f"""
|
||||
const sheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const child = {{repository:'stackchain/dashboard', number:44,
|
||||
url:'https://forge.example/git/stackchain/dashboard/issues/44'}};
|
||||
const childDetail = {{body:'Delivered.\\n\\nRelated to [stackchain/dashboard#12](https://forge.example/git/stackchain/dashboard/issues/12).'}};
|
||||
const parentDetail = {{title:'Launch', updated_at:'2026-08-16T10:00:00Z',
|
||||
body:'Plan\\r\\n - [ ] [Ship mobile flow](https://forge.example/git/stackchain/dashboard/issues/44)\\r\\n- [ ] Other'}};
|
||||
const relationship = sheet.resolveDelegatedParent(child, childDetail, parentDetail);
|
||||
const unrelated = sheet.resolveDelegatedParent(child,
|
||||
{{body:'Related to stackchain/dashboard#12 without a canonical link.'}}, parentDetail);
|
||||
const mismatch = sheet.resolveDelegatedParent(child, childDetail,
|
||||
{{...parentDetail, body:'- [ ] [Different](https://forge.example/git/stackchain/dashboard/issues/45)'}});
|
||||
const incidental = sheet.resolveDelegatedParent(child, childDetail,
|
||||
{{...parentDetail, body:'- [ ] Notes [child](https://forge.example/git/stackchain/dashboard/issues/44)'}});
|
||||
process.stdout.write(JSON.stringify({{relationship, unrelated, mismatch, incidental}}));
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
assert json.loads(completed.stdout) == {
|
||||
"relationship": {
|
||||
"parent": {
|
||||
"repository": "stackchain/dashboard",
|
||||
"number": 12,
|
||||
"url": "https://forge.example/git/stackchain/dashboard/issues/12",
|
||||
},
|
||||
"taskIndex": 0,
|
||||
"alreadyCompleted": False,
|
||||
"checklistComplete": False,
|
||||
},
|
||||
"unrelated": None,
|
||||
"mismatch": None,
|
||||
"incidental": None,
|
||||
}
|
||||
|
||||
|
||||
def test_delegated_parent_completion_changes_only_the_matching_task_marker():
|
||||
script = f"""
|
||||
const complete = require({json.dumps(str(ISSUE_SHEET))}).completeDelegatedParentTask;
|
||||
const childUrl = 'https://forge.example/git/stackchain/dashboard/issues/44';
|
||||
const body = 'Plan\\r\\n - [ ] [Ship mobile flow](' + childUrl + ')\\r\\n' +
|
||||
'- [ ] Duplicate words\\r\\n- [x] [Already](https://forge.example/issues/9)';
|
||||
const changed = complete(body, childUrl);
|
||||
const repeated = complete(changed.body, childUrl);
|
||||
process.stdout.write(JSON.stringify({{changed, repeated}}));
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
assert json.loads(completed.stdout) == {
|
||||
"changed": {
|
||||
"body": "Plan\r\n - [x] [Ship mobile flow](https://forge.example/git/stackchain/dashboard/issues/44)\r\n- [ ] Duplicate words\r\n- [x] [Already](https://forge.example/issues/9)",
|
||||
"taskIndex": 0,
|
||||
"alreadyCompleted": False,
|
||||
"checklistComplete": False,
|
||||
},
|
||||
"repeated": {
|
||||
"body": "Plan\r\n - [x] [Ship mobile flow](https://forge.example/git/stackchain/dashboard/issues/44)\r\n- [ ] Duplicate words\r\n- [x] [Already](https://forge.example/issues/9)",
|
||||
"taskIndex": 0,
|
||||
"alreadyCompleted": True,
|
||||
"checklistComplete": False,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_delegated_parent_completion_reports_when_the_final_task_is_complete():
|
||||
script = f"""
|
||||
const sheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const childUrl = 'https://forge.example/git/stackchain/dashboard/issues/44';
|
||||
const pending = sheet.completeDelegatedParentTask('- [ ] [Ship](' + childUrl + ')', childUrl);
|
||||
const already = sheet.completeDelegatedParentTask('- [x] [Ship](' + childUrl + ')', childUrl);
|
||||
process.stdout.write(JSON.stringify({{pending, already}}));
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
result = json.loads(completed.stdout)
|
||||
assert result["pending"]["checklistComplete"] is True
|
||||
assert result["already"]["checklistComplete"] is True
|
||||
|
||||
|
||||
def test_final_delegated_parent_update_closes_before_acknowledgement_can_continue():
|
||||
script = f"""
|
||||
const finish = require({json.dumps(str(ISSUE_SHEET))}).finishDelegatedParentReview;
|
||||
const childUrl = 'https://forge.example/git/stackchain/dashboard/issues/44';
|
||||
const calls = [];
|
||||
(async () => {{
|
||||
const changed = await finish({{
|
||||
relationship:{{alreadyCompleted:false, checklistComplete:true}},
|
||||
parentItem:{{repository:'stackchain/dashboard', number:12}},
|
||||
parentDetail:{{title:'Launch', body:'- [ ] [Ship](' + childUrl + ')', updated_at:'rev-1'}},
|
||||
childUrl,
|
||||
updateContent:async (_item, payload) => calls.push(['update', payload.body]),
|
||||
closeParent:async () => calls.push(['close']),
|
||||
}});
|
||||
const already = await finish({{
|
||||
relationship:{{alreadyCompleted:true, checklistComplete:true}},
|
||||
parentItem:{{repository:'stackchain/dashboard', number:12}},
|
||||
parentDetail:{{title:'Launch', body:'- [x] [Ship](' + childUrl + ')', updated_at:'rev-2'}},
|
||||
childUrl,
|
||||
updateContent:async () => calls.push(['duplicate-update']),
|
||||
closeParent:async () => calls.push(['retry-close']),
|
||||
}});
|
||||
process.stdout.write(JSON.stringify({{changed, already, calls}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
assert json.loads(completed.stdout) == {
|
||||
"changed": {"updated": True, "closed": True},
|
||||
"already": {"updated": False, "closed": True},
|
||||
"calls": [
|
||||
["update", "- [x] [Ship](https://forge.example/git/stackchain/dashboard/issues/44)"],
|
||||
["close"],
|
||||
["retry-close"],
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_completed_filed_review_offers_parent_completion_before_acknowledgement():
|
||||
markup = (Path(__file__).parents[1] / "frontend" / "index.html").read_text()
|
||||
source = await dashboard()
|
||||
|
||||
assert 'id="complete-parent-and-acknowledge"' in markup
|
||||
assert 'Complete parent step & acknowledge' in markup
|
||||
assert "resolveDelegatedParent(item, detail, parentDetail)" in source
|
||||
handler = source.split("qs('#complete-parent-and-acknowledge').addEventListener('click'", 1)[1].split(
|
||||
"function renderCheckSection", 1
|
||||
)[0]
|
||||
assert "window.confirm" in handler
|
||||
assert "await issueController.finishDelegatedParentReview" in handler
|
||||
assert handler.index("await issueController.finishDelegatedParentReview") < handler.index("acknowledgeCompletedFiled")
|
||||
assert "Complete & close parent · acknowledge" in source
|
||||
|
||||
|
||||
def test_completed_filed_acknowledgement_survives_refresh_until_upstream_update():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
@@ -248,7 +387,9 @@ async def test_completed_filed_sheet_exposes_mobile_acknowledge_and_next_flow():
|
||||
assert "createCompletedFiledReview({" in source
|
||||
assert "lastMyWork = buildMyWork(data)" in source
|
||||
assert "filed: 'filed issues'" in source
|
||||
handler = source.split("qs('#acknowledge-completed-filed').addEventListener('click'", 1)[1]
|
||||
handler = source.split("function acknowledgeCompletedFiled()", 1)[1].split(
|
||||
"qs('#acknowledge-completed-filed').addEventListener", 1
|
||||
)[0]
|
||||
assert "completedFiledReview.acknowledge(selectedIssue)" in handler
|
||||
assert "syncCompletedFiledReviews()" in source
|
||||
assert "api/v1/completed-filed-reviews" in source
|
||||
@@ -2206,12 +2347,16 @@ async def test_mobile_issue_detail_toggles_checklist_with_touch_safe_recovery():
|
||||
html = await dashboard()
|
||||
controller = ISSUE_SHEET.read_text()
|
||||
|
||||
assert "issueController.renderTasks(qs('#issue-sheet-body'), detail, !selectedIssueOffline" in html
|
||||
assert "issueController.renderTasks(qs('#issue-sheet-body'), detail," in html
|
||||
assert "!issueController.readOnly(selectedIssue) && detail.state === 'open'" in html
|
||||
assert "enqueueDurably:message => authoredOutbox.enqueueDurably(message)" in html
|
||||
assert "issueController.bindTaskToggles({" in html
|
||||
assert "container.addEventListener('change', async event =>" in controller
|
||||
assert "event.target.closest('input.task-list-toggle')" in controller
|
||||
assert "state.item, state.detail, Number(control.dataset.taskIndex), control.checked" in controller
|
||||
assert "current:()=>({item:selectedIssue,detail:selectedIssueDetail})" in html
|
||||
assert "current:()=>({item:selectedIssue,detail:selectedIssueDetail,offline:selectedIssueOffline})" in html
|
||||
assert "state.offline ? this.queueTask" in controller
|
||||
assert "status.textContent = 'Checklist queued. Pending sync.'" in controller
|
||||
assert "buildMyWork.replaceIssueContent" in html
|
||||
assert "status.textContent = 'Checklist updated.'" in controller
|
||||
assert "restore(state.detail)" in controller
|
||||
@@ -2220,6 +2365,292 @@ async def test_mobile_issue_detail_toggles_checklist_with_touch_safe_recovery():
|
||||
assert '.checklist-pending .task-list-toggle { opacity:.65;' in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_issue_detail_adds_a_checklist_step_inline_with_accessible_touch_controls():
|
||||
html = await dashboard()
|
||||
|
||||
assert 'id="open-add-checklist-step"' in html
|
||||
assert 'id="add-checklist-step-form"' in html
|
||||
assert 'id="add-checklist-step" type="text"' in html
|
||||
assert 'id="save-checklist-step" type="submit"' in html
|
||||
assert 'id="cancel-checklist-step"' in html
|
||||
assert 'id="add-checklist-step-status" class="small" aria-live="assertive"' in html
|
||||
assert "(selectedIssueOffline ? issueController.queueAddedTask : issueController.addTask).call(" in html
|
||||
assert "applyIssueContent(state.item, state.detail, state.offline ? result.detail : result)" in html
|
||||
assert "Checklist step queued. Pending sync." in html
|
||||
assert "qs('#add-checklist-step').focus()" in html
|
||||
assert "qs('#open-add-checklist-step').focus()" in html
|
||||
assert '.checklist-add button, .checklist-add input { min-height:44px;' in html
|
||||
assert '#issue-sheet.read-only .checklist-add { display:none;' in html
|
||||
assert 'grid-template-columns:minmax(0,1fr) auto auto' in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_issue_detail_manages_checklist_steps_with_touch_safe_inline_editor():
|
||||
html = await dashboard()
|
||||
controller = ISSUE_SHEET.read_text()
|
||||
|
||||
assert 'id="checklist-step-editor"' in html
|
||||
assert 'id="checklist-step-label" type="text"' in html
|
||||
assert 'id="move-checklist-step-earlier"' in html
|
||||
assert 'id="move-checklist-step-later"' in html
|
||||
assert 'id="remove-checklist-step"' in html
|
||||
assert 'id="cancel-checklist-step-edit"' in html
|
||||
assert "manageTasks: Boolean(interactive)" in controller
|
||||
assert "issueController.bindTaskManagement({" in html
|
||||
assert "event.target.closest('button.task-list-manage')" in controller
|
||||
assert "this.queueManagedTask : this.manageTask" in controller
|
||||
assert "globalThis.confirm('Remove this checklist step?')" in controller
|
||||
assert ".task-list-manage { min-width:44px; min-height:44px;" in html
|
||||
assert ".checklist-step-editor button, .checklist-step-editor input { min-height:44px;" in html
|
||||
assert "label.focus()" in controller
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_checklist_manager_files_related_issue_and_links_confirmed_child():
|
||||
html = await dashboard()
|
||||
controller = ISSUE_SHEET.read_text()
|
||||
capture_controller = CREATE_ISSUE_SHEET.read_text()
|
||||
|
||||
assert 'id="file-checklist-step-related" type="button">File as related issue</button>' in html
|
||||
assert "fileRelated, onFileRelated, remove, cancel" in controller
|
||||
assert "onFileRelated({ item:state.item, detail:state.detail, taskIndex:selectedIndex" in controller
|
||||
assert "relatedTaskDraft" in controller
|
||||
assert "linkRelatedTask" in controller
|
||||
assert "startChecklistPromotion" in html
|
||||
assert "createIssueCapture.createChecklistPromotion({" in html
|
||||
assert "checklistPromotion.start(context)" in html
|
||||
assert "checklistPromotion?.cancel()" in html
|
||||
assert "checklistPromotion?.deliveryContext()" in html
|
||||
assert "await issueController.linkRelatedTask(" in capture_controller
|
||||
assert "Related issue created, but the parent link needs attention" in capture_controller
|
||||
assert ".checklist-step-editor button, .checklist-step-editor input { min-height:44px;" in html
|
||||
|
||||
|
||||
def test_checklist_step_promotion_builds_related_draft_and_revision_checked_parent_link():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const createIssueCapture = require({json.dumps(str(CREATE_ISSUE_SHEET))});
|
||||
const calls = [];
|
||||
const controller = createIssueSheet({{
|
||||
storage:null,
|
||||
relatedTaskDraft:createIssueCapture.relatedChecklistDraft,
|
||||
linkRelatedTask:createIssueCapture.linkChecklistTask,
|
||||
fetchJson:async (url, options) => {{
|
||||
calls.push({{url, body:JSON.parse(options.body)}});
|
||||
return {{number:17,title:'Release',body:options && JSON.parse(options.body).body,updated_at:'new'}};
|
||||
}},
|
||||
}});
|
||||
const item = {{repository:'stackchain/api',number:17,url:'https://forge.example/stackchain/api/issues/17'}};
|
||||
const detail = {{title:'Release',body:'Intro\\r\\n - [x] Build package\\r\\n - [ ] Ship',updated_at:'old'}};
|
||||
const draft = controller.relatedTaskDraft(item, detail, 0, ' Build package ');
|
||||
controller.linkRelatedTask(item, detail, 0, {{
|
||||
repository:'stackchain/api',number:44,url:'https://forge.example/stackchain/api/issues/44',title:'Build package',
|
||||
}}).then(result => process.stdout.write(JSON.stringify({{draft,calls,result}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["draft"] == {
|
||||
"repository": "stackchain/api",
|
||||
"title": "Build package",
|
||||
"body": "Related to [stackchain/api#17](https://forge.example/stackchain/api/issues/17).",
|
||||
"labelIds": [],
|
||||
}
|
||||
assert output["calls"] == [{
|
||||
"url": "api/v1/repos/stackchain/api/issues/17/content",
|
||||
"body": {
|
||||
"title": "Release",
|
||||
"body": "Intro\r\n - [x] [Build package](https://forge.example/stackchain/api/issues/44)\r\n - [ ] Ship",
|
||||
"expected_updated_at": "old",
|
||||
},
|
||||
}]
|
||||
assert output["result"]["updated_at"] == "new"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_drafts_reviews_and_retries_an_unambiguous_checklist_conflict():
|
||||
html = await dashboard()
|
||||
|
||||
assert "mergeChecklistConflict: mergeChecklistConflict" in html
|
||||
assert "const checklistConflict = item.checklist_conflict === true" in html
|
||||
assert 'class="draft-review-checklist"' in html
|
||||
assert ">Review changes</button>" in html
|
||||
assert "const latest = await issueController.load({" in html
|
||||
assert "authoredOutbox.resolveIssueContentConflict(item.outbox_id, latest, activeFlushLogin)" in html
|
||||
assert "window.confirm('Apply ' + preview.changes.length + ' checklist change'" in html
|
||||
assert "await authoredOutbox.retry(item.outbox_id, activeFlushLogin)" in html
|
||||
assert "could not be matched safely" in html
|
||||
assert "checklist-conflict.js" in FRONTEND_BUNDLE.read_text()
|
||||
|
||||
|
||||
def test_completed_issue_checklist_offers_close_and_next_during_today():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const controller = createIssueSheet({{storage:null}});
|
||||
const container = {{querySelectorAll:() => [{{checked:true}}, {{checked:true}}]}};
|
||||
process.stdout.write(JSON.stringify(controller.checklistCompletion(container, {{
|
||||
interactive:true, today:true, offline:false,
|
||||
}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output == {
|
||||
"visible": True,
|
||||
"status": "Checklist complete",
|
||||
"label": "Close & next",
|
||||
}
|
||||
|
||||
|
||||
def test_checklist_completion_stays_hidden_when_kept_open():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const controller = createIssueSheet({{storage:null}});
|
||||
const container = {{querySelectorAll:() => [{{checked:true}}]}};
|
||||
process.stdout.write(JSON.stringify(controller.checklistCompletion(container, {{
|
||||
interactive:true, today:false, offline:false, dismissed:true,
|
||||
}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["visible"] is False
|
||||
|
||||
|
||||
def test_checklist_completion_copy_matches_online_and_offline_close_modes():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const controller = createIssueSheet({{storage:null}});
|
||||
const container = {{querySelectorAll:() => [{{checked:true}}]}};
|
||||
process.stdout.write(JSON.stringify({{
|
||||
outside:controller.checklistCompletion(container, {{interactive:true,today:false,offline:false}}),
|
||||
offlineToday:controller.checklistCompletion(container, {{interactive:true,today:true,offline:true}}),
|
||||
offlineOutside:controller.checklistCompletion(container, {{interactive:true,today:false,offline:true}}),
|
||||
}}));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["outside"]["label"] == "Close issue"
|
||||
assert output["offlineToday"] == {
|
||||
"visible": True,
|
||||
"status": "Checklist complete · pending sync",
|
||||
"label": "Queue close & next",
|
||||
}
|
||||
assert output["offlineOutside"]["label"] == "Queue issue closure"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_checklist_completion_bar_reuses_confirmed_close_flow():
|
||||
html = await dashboard()
|
||||
|
||||
assert 'id="checklist-completion"' in html
|
||||
assert 'id="checklist-completion-status" role="status"' in html
|
||||
assert 'id="complete-checklist-issue"' in html
|
||||
assert 'id="keep-checklist-issue-open"' in html
|
||||
assert "function renderChecklistCompletion(detail)" in html
|
||||
assert "issueController.checklistCompletion(qs('#issue-sheet-body')" in html
|
||||
assert "qs('#complete-checklist-issue').addEventListener('click', () =>" in html
|
||||
assert "qs('#close-issue').click()" in html
|
||||
assert "dismissedChecklistBody = selectedIssueDetail?.body" in html
|
||||
assert ".checklist-completion { position:fixed;" in html
|
||||
assert ".checklist-completion button { min-height:44px;" in html
|
||||
assert "padding-bottom:calc(118px + env(safe-area-inset-bottom))" in html
|
||||
|
||||
|
||||
def test_offline_issue_checklist_toggle_waits_for_durable_admission_and_returns_pending_detail():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
let admit; const queued = [];
|
||||
const controller = createIssueSheet({{
|
||||
storage:null,
|
||||
toggleTask:(body, index, checked) => body.replace(index === 0 ? '[ ]' : '[X]', checked ? '[x]' : '[ ]'),
|
||||
enqueueDurably:message => {{ queued.push(message); return new Promise(resolve => admit = resolve); }},
|
||||
}});
|
||||
const item = {{repository:'stackchain/api', number:17}};
|
||||
const detail = {{title:'Release', body:'- [ ] Build\\n- [X] Ship', updated_at:'2026-08-15T10:00:00Z'}};
|
||||
let settled = false;
|
||||
const pending = controller.queueTask(item, detail, 0, true).then(result => {{ settled = true; return result; }});
|
||||
const before = settled;
|
||||
admit({{item:{{id:'queued-check'}}}});
|
||||
pending.then(result => process.stdout.write(JSON.stringify({{before,queued,result}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["before"] is False
|
||||
assert output["queued"] == [{
|
||||
"kind": "issue-content", "repository": "stackchain/api", "number": 17,
|
||||
"title": "Release", "baseBody": "- [ ] Build\n- [X] Ship",
|
||||
"body": "- [x] Build\n- [X] Ship",
|
||||
"expectedUpdatedAt": "2026-08-15T10:00:00Z",
|
||||
}]
|
||||
assert output["result"] == {
|
||||
"queued": True,
|
||||
"detail": {
|
||||
"title": "Release", "body": "- [x] Build\n- [X] Ship",
|
||||
"updated_at": "2026-08-15T10:00:00Z", "checklist_pending": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_offline_issue_checklist_restores_account_bound_pending_body_after_reload():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const controller = createIssueSheet({{storage:null}});
|
||||
const detail = {{title:'Release',body:'- [ ] Build',updated_at:'old'}};
|
||||
const items = [
|
||||
{{kind:'issue-content',repository:'o/r',number:7,ownerLogin:'alexander',title:'Wrong',body:'- [x] Wrong',expectedUpdatedAt:'wrong',status:'queued'}},
|
||||
{{kind:'issue-content',repository:'o/r',number:7,ownerLogin:'timmy',title:'Release',body:'- [x] Build',expectedUpdatedAt:'old',status:'queued'}},
|
||||
];
|
||||
process.stdout.write(JSON.stringify({{
|
||||
restored:controller.pendingTask({{repository:'o/r',number:7}}, detail, items, 'timmy'),
|
||||
isolated:controller.pendingTask({{repository:'o/r',number:7}}, detail, items, 'hou3'),
|
||||
}}));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["restored"] == {
|
||||
"title": "Release", "body": "- [x] Build", "updated_at": "old",
|
||||
"checklist_pending": True,
|
||||
}
|
||||
assert output["isolated"] == {
|
||||
"title": "Release", "body": "- [ ] Build", "updated_at": "old",
|
||||
}
|
||||
|
||||
|
||||
def test_pending_offline_checklist_remains_interactive_for_the_next_change():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
let options = null; const classes = [];
|
||||
const container = {{
|
||||
classList:{{toggle:(name,present)=>classes.push([name,present])}},
|
||||
innerHTML:'',
|
||||
}};
|
||||
const controller = createIssueSheet({{
|
||||
storage:null,
|
||||
renderMarkdown:(body, received)=>{{options=received;return '<label><input class="task-list-toggle"></label>';}}
|
||||
}});
|
||||
controller.renderTasks(container, {{body:'- [x] Build\\n- [ ] Test',checklist_pending:true}}, true);
|
||||
process.stdout.write(JSON.stringify({{options,classes,html:container.innerHTML}}));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["options"] == {"interactiveTasks": True, "manageTasks": True}
|
||||
assert output["classes"] == [["checklist-pending", True]]
|
||||
assert "task-list-toggle" in output["html"]
|
||||
|
||||
|
||||
def test_issue_checklist_toggle_submits_exact_revision_checked_body_once():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
@@ -2260,6 +2691,141 @@ Promise.all([first, duplicate]).then(results => process.stdout.write(JSON.string
|
||||
assert output["confirmed"]["updated_at"] == "2026-08-15T10:01:00Z"
|
||||
|
||||
|
||||
def test_issue_sheet_manages_a_step_through_one_revision_guarded_update():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const calls = [];
|
||||
const controller = createIssueSheet({{
|
||||
storage:null,
|
||||
manageTask:(body,index,operation) => body + `|${{index}}:${{operation.action}}:${{operation.label || ''}}`,
|
||||
fetchJson:(url,options) => {{
|
||||
calls.push({{url,body:JSON.parse(options.body)}});
|
||||
return Promise.resolve({{number:17,title:'Release',body:'- [ ] Build|0:rename:Compile',updated_at:'new'}});
|
||||
}},
|
||||
}});
|
||||
const item = {{repository:'stackchain/api',number:17}};
|
||||
const detail = {{title:'Release',body:'- [ ] Build',updated_at:'old'}};
|
||||
controller.manageTask(item,detail,0,{{action:'rename',label:'Compile'}})
|
||||
.then(result => process.stdout.write(JSON.stringify({{calls,result}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["calls"] == [{
|
||||
"url": "api/v1/repos/stackchain/api/issues/17/content",
|
||||
"body": {
|
||||
"title": "Release", "body": "- [ ] Build|0:rename:Compile",
|
||||
"expected_updated_at": "old",
|
||||
},
|
||||
}]
|
||||
assert output["result"]["updated_at"] == "new"
|
||||
|
||||
|
||||
def test_offline_issue_sheet_manages_a_step_only_after_durable_admission():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
let admit; const queued = [];
|
||||
const controller = createIssueSheet({{
|
||||
storage:null,
|
||||
manageTask:(body,index,operation) => '- [ ] Compile\\n- [x] Test',
|
||||
enqueueDurably:message => {{ queued.push(message); return new Promise(resolve => admit=resolve); }},
|
||||
}});
|
||||
const item = {{repository:'stackchain/api',number:17}};
|
||||
const detail = {{title:'Release',body:'- [ ] Build\\n- [x] Test',updated_at:'old'}};
|
||||
let settled = false;
|
||||
const pending = controller.queueManagedTask(item,detail,0,{{action:'rename',label:'Compile'}})
|
||||
.then(result => {{settled=true;return result;}});
|
||||
const before = settled;
|
||||
admit({{item:{{id:'manage-step'}}}});
|
||||
pending.then(result => process.stdout.write(JSON.stringify({{before,queued,result}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["before"] is False
|
||||
assert output["queued"] == [{
|
||||
"kind": "issue-content", "repository": "stackchain/api", "number": 17,
|
||||
"title": "Release", "baseBody": "- [ ] Build\n- [x] Test",
|
||||
"body": "- [ ] Compile\n- [x] Test", "expectedUpdatedAt": "old",
|
||||
"checklistOperation": {"action": "rename", "index": 0, "label": "Compile"},
|
||||
}]
|
||||
assert output["result"]["detail"]["checklist_pending"] is True
|
||||
assert output["result"]["detail"]["body"] == "- [ ] Compile\n- [x] Test"
|
||||
|
||||
|
||||
def test_issue_sheet_adds_a_validated_unchecked_step_without_replacing_existing_content():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
const calls = [];
|
||||
const controller = createIssueSheet({{
|
||||
storage:null,
|
||||
fetchJson:(url, options) => {{
|
||||
calls.push({{url, body:JSON.parse(options.body)}});
|
||||
return Promise.resolve({{number:17,title:'Release',body:'Intro\\n\\n- [x] Build\\n- [ ] Verify rollback',updated_at:'new'}});
|
||||
}},
|
||||
}});
|
||||
const item = {{repository:'stackchain/api',number:17}};
|
||||
const detail = {{title:'Release',body:'Intro\\n\\n- [x] Build',updated_at:'old'}};
|
||||
Promise.all([
|
||||
controller.addTask(item, detail, ' Verify rollback '),
|
||||
controller.addTask(item, detail, ' build ').catch(error => ({{error:error.message}})),
|
||||
controller.addTask(item, detail, ' ').catch(error => ({{error:error.message}})),
|
||||
]).then(results => process.stdout.write(JSON.stringify({{calls,results}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["calls"] == [{
|
||||
"url": "api/v1/repos/stackchain/api/issues/17/content",
|
||||
"body": {
|
||||
"title": "Release",
|
||||
"body": "Intro\n\n- [x] Build\n- [ ] Verify rollback",
|
||||
"expected_updated_at": "old",
|
||||
},
|
||||
}]
|
||||
assert output["results"][0]["body"].endswith("- [ ] Verify rollback")
|
||||
assert output["results"][1] == {"error": "That checklist step already exists."}
|
||||
assert output["results"][2] == {"error": "Enter a checklist step."}
|
||||
|
||||
|
||||
def test_offline_issue_sheet_adds_a_step_only_after_durable_admission():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
let admit; const queued = [];
|
||||
const controller = createIssueSheet({{
|
||||
storage:null,
|
||||
enqueueDurably:message => {{ queued.push(message); return new Promise(resolve => admit=resolve); }},
|
||||
}});
|
||||
const item = {{repository:'stackchain/api',number:17}};
|
||||
const detail = {{title:'Release',body:'Intro',updated_at:'old'}};
|
||||
let settled = false;
|
||||
const pending = controller.queueAddedTask(item, detail, 'Verify rollback').then(result => {{settled=true;return result;}});
|
||||
const before = settled;
|
||||
admit({{item:{{id:'add-step'}}}});
|
||||
pending.then(result => process.stdout.write(JSON.stringify({{before,queued,result}})));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["before"] is False
|
||||
assert output["queued"] == [{
|
||||
"kind": "issue-content", "repository": "stackchain/api", "number": 17,
|
||||
"title": "Release", "baseBody": "Intro", "body": "Intro\n- [ ] Verify rollback",
|
||||
"expectedUpdatedAt": "old",
|
||||
}]
|
||||
assert output["result"] == {
|
||||
"queued": True,
|
||||
"detail": {
|
||||
"title": "Release", "body": "Intro\n- [ ] Verify rollback",
|
||||
"updated_at": "old", "checklist_pending": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_issue_content_edit_is_single_flight_and_keeps_scoped_draft_until_confirmed():
|
||||
script = f"""
|
||||
const createIssueSheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
|
||||
@@ -410,7 +410,7 @@ async def test_plan_today_wires_cancel_back_and_success_through_overlay_history(
|
||||
def test_plan_today_controller_is_available_in_the_offline_shell():
|
||||
source = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/plan-today.js'" in source
|
||||
assert "BASE + 'static/plan-today-readiness.js'" in source
|
||||
assert "BASE + 'static/plan-today-preview.js'" in source
|
||||
@@ -30,6 +30,7 @@ process.stdout.write(JSON.stringify(databases));
|
||||
"stackchain-background-outbox-v1",
|
||||
"stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-voice-transcripts-v1",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -47,6 +47,7 @@ const clear = createPrivateDeviceDataPurger({{
|
||||
"stackchain-background-outbox-v1",
|
||||
"stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert state["caches"] == ["stackchain-dashboard-shell-v37"]
|
||||
assert state["workerMessages"] == [{"type": "stackchain-purge-outbox"}]
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RECONNECT = ROOT / "frontend" / "reconnect-outboxes.js"
|
||||
|
||||
|
||||
def run_node(script: str) -> dict:
|
||||
result = subprocess.run(
|
||||
["node", "-e", script], cwd=ROOT, text=True, capture_output=True, check=True
|
||||
)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def test_successful_reconnect_restores_identity_and_flushes_unchanged_outboxes():
|
||||
result = run_node(
|
||||
f"""
|
||||
const createReconnectOutboxes = require({json.dumps(str(RECONNECT))});
|
||||
const calls = [];
|
||||
const reconnect = createReconnectOutboxes({{
|
||||
refresh: async () => ({{context:{{user:{{login:'timmy'}}}}}}),
|
||||
restoreIdentity: login => calls.push(['identity', login]),
|
||||
flushIssue: () => calls.push(['issue']),
|
||||
flushAuthored: () => calls.push(['authored']),
|
||||
flushNotificationReads: () => calls.push(['notification-read']),
|
||||
}});
|
||||
reconnect().then(result => process.stdout.write(JSON.stringify({{result, calls}})));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result == {
|
||||
"result": True,
|
||||
"calls": [
|
||||
["identity", "timmy"],
|
||||
["issue"],
|
||||
["authored"],
|
||||
["notification-read"],
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_dashboard_uses_reconnect_flush_after_live_identity_refresh():
|
||||
index = (ROOT / "frontend" / "index.html").read_text()
|
||||
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
|
||||
|
||||
assert '<script src="static/reconnect-outboxes.js"></script>' in index
|
||||
assert "const reconnectOutboxes = createReconnectOutboxes({" in dashboard
|
||||
assert "restoreIdentity: login => { activeFlushLogin = login; confirmedOwnerLogin = login; }" in dashboard
|
||||
assert "window.addEventListener('online', reconnectOutboxes);" in dashboard
|
||||
@@ -14,7 +14,10 @@ REQUIRED_HEADERS = {
|
||||
def assert_browser_security_boundary(response: httpx.Response) -> None:
|
||||
for name, value in REQUIRED_HEADERS.items():
|
||||
assert response.headers[name] == value
|
||||
assert "camera=()" in response.headers["permissions-policy"]
|
||||
permissions_policy = response.headers["permissions-policy"]
|
||||
assert "camera=()" in permissions_policy
|
||||
assert "microphone=(self)" in permissions_policy
|
||||
assert "microphone=()" not in permissions_policy
|
||||
policy = response.headers["content-security-policy"]
|
||||
assert "default-src 'self'" in policy
|
||||
assert "script-src 'self'" in policy
|
||||
|
||||
@@ -155,7 +155,7 @@ async function dispatchPush(payload) {{
|
||||
def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/my-work.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
@@ -164,14 +164,14 @@ def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
def test_ownership_exit_runtime_rolls_the_offline_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
|
||||
def test_offline_review_next_ships_today_completion_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/today-completion.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -179,22 +179,32 @@ def test_offline_review_next_ships_today_completion_atomically():
|
||||
def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/create-issue-sheet.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
|
||||
def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/issue-sheet.js'" in source
|
||||
assert "BASE + 'static/checklist-conflict.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
|
||||
|
||||
def test_exact_later_picker_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/later-picker.js'" in source
|
||||
|
||||
|
||||
def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/install-app.js'" in source
|
||||
@@ -203,21 +213,21 @@ def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
def test_today_convergence_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
def test_mobile_search_viewport_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/mobile-search-viewport.js'" in source
|
||||
|
||||
|
||||
def test_update_ownership_flow_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/update-ownership.js'" in source
|
||||
|
||||
|
||||
@@ -402,6 +412,7 @@ def test_revoked_background_session_purges_worker_data_and_notifies_dashboard_cl
|
||||
"stackchain-background-outbox-v1",
|
||||
"stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["state"]["deleted"] == ["stackchain-dashboard-old"]
|
||||
assert result["state"]["clientMessages"] == [
|
||||
@@ -494,6 +505,7 @@ def test_device_purge_message_stops_worker_outbox_and_acknowledges_completion():
|
||||
"stackchain-background-outbox-v1",
|
||||
"stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["replies"] == [{"ok": True}]
|
||||
|
||||
@@ -881,7 +893,7 @@ def test_one_session_bound_csrf_proof_is_reused_for_a_background_drain():
|
||||
def test_queue_today_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/queue-today.js'" in source
|
||||
|
||||
|
||||
@@ -920,6 +932,7 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/draft-capacity-dialog.js",
|
||||
"/dashboard/static/outbox-coordinator.js",
|
||||
"/dashboard/static/issue-outbox.js",
|
||||
"/dashboard/static/reconnect-outboxes.js",
|
||||
"/dashboard/static/authored-outbox.js",
|
||||
"/dashboard/static/offline-issue-close.js",
|
||||
"/dashboard/static/offline-issue-blocker.js",
|
||||
@@ -961,6 +974,9 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/issue-attachment.js",
|
||||
"/dashboard/static/issue-filing-review.js",
|
||||
"/dashboard/static/issue-sheet.js",
|
||||
"/dashboard/static/checklist-conflict.js",
|
||||
"/dashboard/static/voice-transcript-store.js",
|
||||
"/dashboard/static/voice-issue-capture.js",
|
||||
"/dashboard/static/create-issue-sheet.js",
|
||||
"/dashboard/static/create-and-start.js",
|
||||
"/dashboard/static/assign-and-start.js",
|
||||
@@ -1091,6 +1107,7 @@ def test_expired_offline_lease_purges_private_worker_data_and_refuses_cached_she
|
||||
"stackchain-background-outbox-v1",
|
||||
"stackchain-offline-work-v2",
|
||||
"stackchain-unfiled-captures-v1",
|
||||
"stackchain-voice-transcripts-v1",
|
||||
]
|
||||
assert result["state"]["deleted"] == ["stackchain-dashboard-old"]
|
||||
assert "private cached dashboard" not in result["body"]
|
||||
|
||||
@@ -221,7 +221,7 @@ async def test_today_blocker_opens_existing_preview_and_preserves_readiness_gate
|
||||
def test_readiness_runtime_is_available_in_offline_shell():
|
||||
service_worker = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v107';" in service_worker
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v108';" in service_worker
|
||||
assert "BASE + 'static/today-readiness.js'" in service_worker
|
||||
|
||||
|
||||
|
||||
@@ -127,7 +127,7 @@ sync.enqueueConfiguration(120, {{'issue:r:1:':60}});
|
||||
def test_inflight_today_drain_ships_in_a_new_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v107" in source
|
||||
assert "stackchain-dashboard-shell-v108" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
from src.frontend_bundle import build_frontend
|
||||
|
||||
|
||||
VOICE_CAPTURE = Path(__file__).parents[1] / "frontend" / "voice-issue-capture.js"
|
||||
VOICE_STORE = Path(__file__).parents[1] / "frontend" / "voice-transcript-store.js"
|
||||
FRONTEND = VOICE_CAPTURE.parent
|
||||
|
||||
|
||||
def run_node(script: str):
|
||||
completed = subprocess.run(
|
||||
["node", "-e", script], capture_output=True, text=True
|
||||
)
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
return json.loads(completed.stdout)
|
||||
|
||||
|
||||
def test_transcript_maps_first_sentence_to_title_and_remainder_to_note_with_field_limits():
|
||||
script = f"""
|
||||
const {{mapVoiceTranscript}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
const mapped = mapVoiceTranscript(' Lift outage on level four. Elevator B is trapped. ');
|
||||
const bounded = mapVoiceTranscript('x'.repeat(300) + '. ' + 'y'.repeat(10100));
|
||||
process.stdout.write(JSON.stringify({{mapped, titleLength:bounded.title.length, bodyLength:bounded.body.length}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"mapped": {
|
||||
"title": "Lift outage on level four.",
|
||||
"body": "Elevator B is trapped.",
|
||||
},
|
||||
"titleLength": 255,
|
||||
"bodyLength": 10000,
|
||||
}
|
||||
|
||||
|
||||
def test_explicit_tap_starts_recognition_and_final_transcript_waits_for_review():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false; this.value=''; this.textContent=''; this.listeners={{}}; }}
|
||||
addEventListener(name, callback) {{ this.listeners[name]=callback; }}
|
||||
click() {{ this.listeners.click?.({{currentTarget:this}}); }}
|
||||
dispatchEvent() {{}}
|
||||
}}
|
||||
let instance;
|
||||
class Recognition {{
|
||||
constructor() {{ instance=this; this.started=0; }}
|
||||
start() {{ this.started += 1; }}
|
||||
stop() {{}}
|
||||
abort() {{}}
|
||||
}}
|
||||
const elements = Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
elements.review.hidden=true;
|
||||
const controller = createVoiceIssueCapture({{Recognition,elements}});
|
||||
const before = {{started:Boolean(instance), rootHidden:elements.root.hidden}};
|
||||
elements.start.click();
|
||||
instance.onresult({{results:[Object.assign([{{transcript:'Lift outage. Elevator B is trapped.'}}], {{isFinal:true}})]}});
|
||||
process.stdout.write(JSON.stringify({{
|
||||
supported:controller.supported, before, started:instance.started,
|
||||
listening:elements.status.textContent, transcript:elements.transcript.value,
|
||||
reviewHidden:elements.review.hidden, title:elements.title.value, body:elements.body.value,
|
||||
appendLabel:elements.append.textContent, replaceHidden:elements.replace.hidden
|
||||
}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"supported": True,
|
||||
"before": {"started": False, "rootHidden": False},
|
||||
"started": 1,
|
||||
"listening": "Transcript ready. Review it before using it.",
|
||||
"transcript": "Lift outage. Elevator B is trapped.",
|
||||
"reviewHidden": False,
|
||||
"title": "",
|
||||
"body": "",
|
||||
"appendLabel": "Use transcript",
|
||||
"replaceHidden": True,
|
||||
}
|
||||
|
||||
|
||||
def test_final_transcript_is_checkpointed_for_the_confirmed_account():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false; this.value=''; this.textContent=''; this.listeners={{}}; }}
|
||||
addEventListener(name, callback) {{ this.listeners[name]=callback; }}
|
||||
click() {{ this.listeners.click?.({{currentTarget:this}}); }}
|
||||
dispatchEvent() {{}}
|
||||
}}
|
||||
let recognition;
|
||||
class Recognition {{
|
||||
constructor() {{ recognition=this; }} start() {{}} stop() {{}} abort() {{}}
|
||||
}}
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','discard','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
elements.review.hidden=true;
|
||||
const saved=[];
|
||||
const transcriptStore={{
|
||||
async load() {{ return ''; }},
|
||||
async save(login, transcript) {{ saved.push({{login, transcript}}); }},
|
||||
async clear() {{}},
|
||||
}};
|
||||
(async () => {{
|
||||
const controller=createVoiceIssueCapture({{
|
||||
Recognition,elements,transcriptStore,getLogin:()=> 'timmy'
|
||||
}});
|
||||
await controller.ready;
|
||||
elements.start.click();
|
||||
recognition.onresult({{results:[Object.assign([{{transcript:'Lift outage.'}}], {{isFinal:true}})]}});
|
||||
await Promise.resolve();
|
||||
process.stdout.write(JSON.stringify({{saved, transcript:elements.transcript.value}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"saved": [{"login": "timmy", "transcript": "Lift outage."}],
|
||||
"transcript": "Lift outage.",
|
||||
}
|
||||
|
||||
|
||||
def test_pending_transcript_recovers_only_for_the_confirmed_account():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false; this.value=''; this.textContent=''; this.listeners={{}}; }}
|
||||
addEventListener(name, callback) {{ this.listeners[name]=callback; }}
|
||||
dispatchEvent() {{}}
|
||||
}}
|
||||
class Recognition {{ start() {{}} stop() {{}} abort() {{}} }}
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','discard','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
elements.review.hidden=true;
|
||||
const loads=[];
|
||||
(async () => {{
|
||||
const controller=createVoiceIssueCapture({{
|
||||
Recognition,elements,getLogin:()=> 'timmy',
|
||||
transcriptStore:{{
|
||||
async load(login) {{ loads.push(login); return 'Recovered lift outage.'; }},
|
||||
async save() {{}}, async clear() {{}},
|
||||
}},
|
||||
}});
|
||||
await controller.ready;
|
||||
process.stdout.write(JSON.stringify({{
|
||||
loads, transcript:elements.transcript.value, reviewHidden:elements.review.hidden,
|
||||
status:elements.status.textContent
|
||||
}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"loads": ["timmy"],
|
||||
"transcript": "Recovered lift outage.",
|
||||
"reviewHidden": False,
|
||||
"status": "Recovered transcript. Review it before using or discarding it.",
|
||||
}
|
||||
|
||||
|
||||
def test_multiple_final_segments_accumulate_in_one_bounded_checkpoint():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false; this.value=''; this.textContent=''; this.listeners={{}}; }}
|
||||
addEventListener(name, callback) {{ this.listeners[name]=callback; }}
|
||||
click() {{ this.listeners.click?.(); }} dispatchEvent() {{}}
|
||||
}}
|
||||
let recognition;
|
||||
class Recognition {{ constructor() {{ recognition=this; }} start() {{}} stop() {{}} abort() {{}} }}
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','discard','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
const saved=[];
|
||||
(async () => {{
|
||||
const controller=createVoiceIssueCapture({{Recognition,elements,getLogin:()=> 'timmy',transcriptStore:{{
|
||||
async load() {{ return ''; }}, async save(login,text) {{ saved.push(text); }}, async clear() {{}},
|
||||
}}}});
|
||||
await controller.ready; elements.start.click();
|
||||
recognition.onresult({{results:[Object.assign([{{transcript:'Lift outage.'}}],{{isFinal:true}})]}});
|
||||
recognition.onresult({{results:[Object.assign([{{transcript:'Elevator B is trapped.'}}],{{isFinal:true}})]}});
|
||||
await Promise.resolve();
|
||||
process.stdout.write(JSON.stringify({{transcript:elements.transcript.value,saved}}));
|
||||
}})().catch(error=>{{console.error(error);process.exit(1);}});
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"transcript": "Lift outage. Elevator B is trapped.",
|
||||
"saved": ["Lift outage.", "Lift outage. Elevator B is trapped."],
|
||||
}
|
||||
|
||||
|
||||
def test_apply_and_discard_each_clear_the_consumed_checkpoint():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false;this.value='';this.textContent='';this.listeners={{}}; }}
|
||||
addEventListener(name,callback) {{ this.listeners[name]=callback; }}
|
||||
click() {{ this.listeners.click?.(); }} dispatchEvent() {{}}
|
||||
}}
|
||||
class Recognition {{ start(){{}} stop(){{}} abort(){{}} }}
|
||||
async function setup() {{
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','discard','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
const cleared=[];
|
||||
const controller=createVoiceIssueCapture({{Recognition,elements,getLogin:()=> 'timmy',transcriptStore:{{
|
||||
async load() {{ return 'Recovered lift outage.'; }}, async save() {{}},
|
||||
async clear(login) {{ cleared.push(login); }},
|
||||
}}}});
|
||||
await controller.ready;
|
||||
return {{elements,cleared}};
|
||||
}}
|
||||
(async () => {{
|
||||
const applied=await setup(); applied.elements.append.click(); await Promise.resolve();
|
||||
const discarded=await setup(); discarded.elements.discard.click(); await Promise.resolve();
|
||||
process.stdout.write(JSON.stringify({{
|
||||
applied:{{cleared:applied.cleared,reviewHidden:applied.elements.review.hidden,title:applied.elements.title.value}},
|
||||
discarded:{{cleared:discarded.cleared,reviewHidden:discarded.elements.review.hidden,transcript:discarded.elements.transcript.value,status:discarded.elements.status.textContent}}
|
||||
}}));
|
||||
}})().catch(error=>{{console.error(error);process.exit(1);}});
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"applied": {
|
||||
"cleared": ["timmy"],
|
||||
"reviewHidden": True,
|
||||
"title": "Recovered lift outage.",
|
||||
},
|
||||
"discarded": {
|
||||
"cleared": ["timmy"],
|
||||
"reviewHidden": True,
|
||||
"transcript": "",
|
||||
"status": "Recovered transcript discarded.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_review_requires_explicit_append_or_replace_when_typed_content_exists():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false; this.value=''; this.textContent=''; this.listeners={{}}; this.events=[]; }}
|
||||
addEventListener(name, callback) {{ this.listeners[name]=callback; }}
|
||||
click() {{ this.listeners.click?.({{currentTarget:this}}); }}
|
||||
dispatchEvent(event) {{ this.events.push(event.type); }}
|
||||
}}
|
||||
function setup() {{
|
||||
let instance;
|
||||
class Recognition {{
|
||||
constructor() {{ instance=this; }} start() {{}} stop() {{}} abort() {{}}
|
||||
}}
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
elements.title.value='Existing title'; elements.body.value='Existing note'; elements.review.hidden=true;
|
||||
createVoiceIssueCapture({{Recognition,elements, createEvent:name=>({{type:name}})}});
|
||||
elements.start.click();
|
||||
instance.onresult({{results:[Object.assign([{{transcript:'Lift outage. Elevator B is trapped.'}}], {{isFinal:true}})]}});
|
||||
return elements;
|
||||
}}
|
||||
const appended=setup(); appended.append.click();
|
||||
const replaced=setup(); replaced.replace.click();
|
||||
process.stdout.write(JSON.stringify({{
|
||||
appended:{{title:appended.title.value,body:appended.body.value,events:[appended.title.events,appended.body.events]}},
|
||||
replaced:{{title:replaced.title.value,body:replaced.body.value,events:[replaced.title.events,replaced.body.events]}}
|
||||
}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"appended": {
|
||||
"title": "Existing title",
|
||||
"body": "Existing note\n\nLift outage.\n\nElevator B is trapped.",
|
||||
"events": [["input"], ["input"]],
|
||||
},
|
||||
"replaced": {
|
||||
"title": "Lift outage.",
|
||||
"body": "Elevator B is trapped.",
|
||||
"events": [["input"], ["input"]],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_unsupported_browser_keeps_keyboard_flow_and_exposes_no_voice_control():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
const element=()=>({{hidden:false,textContent:'',addEventListener(){{}}}});
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','status','title','body'].map(key=>[key,element()])
|
||||
);
|
||||
const controller=createVoiceIssueCapture({{Recognition:null,elements}});
|
||||
process.stdout.write(JSON.stringify({{
|
||||
supported:controller.supported, hidden:elements.root.hidden, guidance:elements.status.textContent
|
||||
}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"supported": False,
|
||||
"hidden": True,
|
||||
"guidance": "Voice capture is unavailable; type the title and note instead.",
|
||||
}
|
||||
|
||||
|
||||
def test_recognition_start_rejection_restores_controls_and_preserves_draft():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false; this.value=''; this.textContent=''; this.listeners={{}}; }}
|
||||
addEventListener(name, callback) {{ this.listeners[name]=callback; }}
|
||||
click() {{ this.listeners.click?.({{currentTarget:this}}); }} dispatchEvent() {{}}
|
||||
}}
|
||||
class Recognition {{
|
||||
start() {{ throw new Error('microphone blocked by browser policy'); }}
|
||||
stop() {{}} abort() {{}}
|
||||
}}
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
elements.title.value='Existing title';
|
||||
elements.body.value='Existing note';
|
||||
elements.transcript.value='Recovered transcript.';
|
||||
elements.start.hidden=false; elements.stop.hidden=true;
|
||||
createVoiceIssueCapture({{Recognition,elements}});
|
||||
elements.start.click();
|
||||
process.stdout.write(JSON.stringify({{
|
||||
startHidden:elements.start.hidden, stopHidden:elements.stop.hidden,
|
||||
status:elements.status.textContent, title:elements.title.value,
|
||||
body:elements.body.value, transcript:elements.transcript.value
|
||||
}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"startHidden": False,
|
||||
"stopHidden": True,
|
||||
"status": "Voice capture could not start. Your draft and transcript are unchanged.",
|
||||
"title": "Existing title",
|
||||
"body": "Existing note",
|
||||
"transcript": "Recovered transcript.",
|
||||
}
|
||||
|
||||
|
||||
def test_stop_error_and_sheet_close_release_recognition_without_losing_transcript():
|
||||
script = f"""
|
||||
const {{createVoiceIssueCapture}} = require({json.dumps(str(VOICE_CAPTURE))});
|
||||
class Element {{
|
||||
constructor() {{ this.hidden=false; this.value=''; this.textContent=''; this.listeners={{}}; }}
|
||||
addEventListener(name, callback) {{ this.listeners[name]=callback; }}
|
||||
click() {{ this.listeners.click?.({{currentTarget:this}}); }} dispatchEvent() {{}}
|
||||
}}
|
||||
let instance;
|
||||
class Recognition {{
|
||||
constructor() {{ instance=this; this.stops=0; this.aborts=0; }}
|
||||
start() {{}} stop() {{ this.stops+=1; }} abort() {{ this.aborts+=1; }}
|
||||
}}
|
||||
const elements=Object.fromEntries(
|
||||
['root','start','stop','review','transcript','append','replace','status','title','body'].map(key=>[key,new Element()])
|
||||
);
|
||||
const controller=createVoiceIssueCapture({{Recognition,elements}});
|
||||
elements.start.click();
|
||||
instance.onresult({{results:[Object.assign([{{transcript:'Partial final transcript.'}}], {{isFinal:true}})]}});
|
||||
elements.stop.click();
|
||||
const afterStop=elements.status.textContent;
|
||||
instance.onerror({{error:'not-allowed'}});
|
||||
const afterError=elements.status.textContent;
|
||||
controller.cancel();
|
||||
process.stdout.write(JSON.stringify({{
|
||||
stops:instance.stops, aborts:instance.aborts, afterStop, afterError,
|
||||
transcript:elements.transcript.value, reviewHidden:elements.review.hidden
|
||||
}}));
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"stops": 1,
|
||||
"aborts": 1,
|
||||
"afterStop": "Finishing transcript…",
|
||||
"afterError": "Microphone permission was denied. Your draft and transcript are unchanged.",
|
||||
"transcript": "Partial final transcript.",
|
||||
"reviewHidden": False,
|
||||
}
|
||||
|
||||
|
||||
def test_private_store_isolates_bounded_transcripts_by_normalized_account():
|
||||
script = f"""
|
||||
const createVoiceTranscriptStore=require({json.dumps(str(VOICE_STORE))});
|
||||
const records=new Map();
|
||||
const transaction=async work=>work({{
|
||||
get:async key=>records.get(key),
|
||||
put:async value=>records.set(value.login,{{...value}}),
|
||||
delete:async key=>records.delete(key),
|
||||
}});
|
||||
(async()=>{{
|
||||
const store=createVoiceTranscriptStore({{transaction}});
|
||||
await store.save(' Timmy ', ' Lift outage. ' + 'x'.repeat(11000));
|
||||
await store.save('alexander', 'Private second account');
|
||||
const before={{timmy:await store.load('timmy'),alexander:await store.load('alexander')}};
|
||||
await store.clear('TIMMY');
|
||||
process.stdout.write(JSON.stringify({{
|
||||
before,after:await store.load('timmy'),keys:[...records.keys()],length:before.timmy.length
|
||||
}}));
|
||||
}})().catch(error=>{{console.error(error);process.exit(1);}});
|
||||
"""
|
||||
assert run_node(script) == {
|
||||
"before": {
|
||||
"timmy": "Lift outage. " + "x" * 10242,
|
||||
"alexander": "Private second account",
|
||||
},
|
||||
"after": "",
|
||||
"keys": ["alexander"],
|
||||
"length": 10255,
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_new_sheet_ships_accessible_voice_review_inside_issue_capture_feature():
|
||||
build = build_frontend(FRONTEND)
|
||||
html = build.dashboard_html
|
||||
capture_bundle = build.feature_bundles["issue-capture"].runtime_bytes
|
||||
dashboard = (FRONTEND / "dashboard.js").read_text()
|
||||
|
||||
assert 'id="voice-issue-capture"' in html
|
||||
assert 'id="start-voice-issue-capture"' in html
|
||||
assert 'id="stop-voice-issue-capture"' in html
|
||||
assert 'id="voice-issue-transcript"' in html
|
||||
assert 'id="voice-issue-status" class="small" aria-live="polite"' in html
|
||||
assert 'id="append-voice-issue-transcript"' in html
|
||||
assert 'id="replace-with-voice-issue-transcript"' in html
|
||||
assert 'id="discard-voice-issue-transcript"' in html
|
||||
assert b"function createVoiceIssueCapture" in capture_bundle
|
||||
assert b"function createVoiceTranscriptStore" in capture_bundle
|
||||
assert b"function createVoiceIssueCapture" not in build.runtime_bytes
|
||||
assert "window.SpeechRecognition || window.webkitSpeechRecognition" in dashboard
|
||||
assert "transcriptStore:createVoiceTranscriptStore()" in dashboard
|
||||
assert "getLogin:()=>confirmedOwnerLogin" in dashboard
|
||||
assert "voiceIssueCapture.cancel();" in dashboard
|
||||
registry = run_node(
|
||||
f"process.stdout.write(JSON.stringify(require({json.dumps(str(FRONTEND / 'private-data-registry.js'))})))"
|
||||
)
|
||||
assert "stackchain-voice-transcripts-v1" in registry
|
||||
Reference in new issue
Block a user