Compare commits

...
Author SHA1 Message Date
timmy e125019f57 Merge pull request 'Annotate mobile evidence before filing' (#832) from timmy/831-annotate-mobile-evidence into main
CI / lint (push) Successful in 1m55s
CI / build-release (push) Successful in 6s
CI / release-candidate (push) Successful in 7s
2026-08-14 14:59:50 +00:00
timmy 6ba823abd2 feat: annotate mobile evidence before filing (Closes #831)
CI / lint (pull_request) Successful in 1m43s
CI / build-release (pull_request) Successful in 5s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 14:57:17 +00:00
timmy f44fa6e579 Crop and redact mobile evidence before filing (#830)
CI / lint (push) Successful in 1m41s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 6s
Closes #829
2026-08-14 14:36:29 +00:00
timmy 87ff83bd2d feat: crop and redact mobile evidence (Closes #829)
CI / lint (pull_request) Successful in 1m49s
CI / build-release (pull_request) Successful in 5s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 14:33:18 +00:00
timmy 7dd396154d Merge pull request 'Explain each mobile evidence screenshot before filing' (#828) from timmy/827-evidence-screenshot-notes into main
CI / lint (push) Successful in 1m51s
CI / build-release (push) Successful in 6s
CI / release-candidate (push) Successful in 6s
2026-08-14 13:44:13 +00:00
timmy af5fe9b69d feat: explain mobile evidence screenshots (Closes #827)
CI / lint (pull_request) Successful in 1m47s
CI / build-release (pull_request) Successful in 6s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 13:41:02 +00:00
timmy 807364c63b Merge pull request 'Review and reorder mobile evidence before filing' (#826) from timmy/825-review-reorder-mobile-evidence into main
CI / lint (push) Successful in 1m46s
CI / build-release (push) Successful in 6s
CI / release-candidate (push) Successful in 6s
2026-08-14 12:47:07 +00:00
timmy 6315323a48 feat: review and reorder mobile evidence (Closes #825)
CI / lint (pull_request) Successful in 1m46s
CI / build-release (pull_request) Successful in 7s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 12:43:31 +00:00
timmy 6a9271cabb Merge pull request 'Capture mobile evidence bundles with one issue' (#824)
CI / lint (push) Successful in 1m49s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 6s
Closes #823
2026-08-14 11:45:28 +00:00
timmy a1c56bd644 feat: capture mobile evidence bundles (Closes #823)
CI / lint (pull_request) Successful in 1m42s
CI / build-release (pull_request) Successful in 6s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 11:43:01 +00:00
timmy ebc3b9ee4d Merge pull request 'Save and reopen synced mobile Search views' (#822)
CI / lint (push) Successful in 1m48s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 6s
Closes #821
2026-08-14 10:49:01 +00:00
timmy 19772b5797 feat: sync saved mobile search views (Closes #821)
CI / lint (pull_request) Successful in 1m46s
CI / build-release (pull_request) Successful in 5s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 10:46:13 +00:00
timmy 6314efb82b Merge pull request 'feat: Fix flaky live-snapshot freshness test blocking CI release' (#820) from timmy/819-fix-flaky-live-snapshot-freshness-test-blocking- into main
CI / lint (push) Successful in 1m44s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 5s
2026-08-14 10:24:46 +00:00
timmy 5cda95eeb2 test: remove scheduler race from snapshot freshness check
CI / lint (pull_request) Successful in 1m41s
CI / build-release (pull_request) Successful in 5s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 10:14:09 +00:00
timmy 0c71dea00c Merge pull request 'Apply mobile Search release plans atomically' (#818) from timmy/817-atomic-search-release-plan into main
CI / lint (push) Failing after 1m54s
CI / build-release (push) Has been skipped
CI / release-candidate (push) Has been skipped
2026-08-14 10:00:02 +00:00
timmy 53539e0cdf feat: apply search release plans atomically (Closes #817)
CI / lint (pull_request) Successful in 1m43s
CI / build-release (pull_request) Successful in 6s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 09:57:15 +00:00
timmy 9a24aff537 Merge pull request 'Plan selected mobile Search issues into a release milestone' (#816) from timmy/815-plan-search-release into main
CI / lint (push) Successful in 1m38s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 5s
Plan selected mobile Search issues into a release milestone (#816)
2026-08-14 09:34:28 +00:00
timmy 43769460fc feat: plan search batches into releases (Closes #815)
CI / lint (pull_request) Successful in 1m37s
CI / build-release (pull_request) Successful in 5s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 09:30:53 +00:00
timmy 2e62eb09f5 Merge pull request 'Batch-schedule selected mobile Search issues into Later' (#814) from timmy/813-batch-defer-search-results into main
CI / lint (push) Successful in 1m36s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 7s
2026-08-14 09:08:14 +00:00
timmy 1ef3e291c2 feat: batch-defer mobile search results (Closes #813)
CI / lint (pull_request) Successful in 1m36s
CI / build-release (pull_request) Successful in 5s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 09:05:30 +00:00
timmy 3694f2501b Merge pull request 'Fit mobile Search batches to Today time capacity' (#812) from timmy/811-search-batch-time-capacity into main
CI / lint (push) Successful in 1m38s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 5s
2026-08-14 08:31:24 +00:00
timmy c3d58d7111 feat: fit search batches to Today capacity (Closes #811)
CI / lint (pull_request) Successful in 1m43s
CI / build-release (pull_request) Successful in 6s
CI / release-candidate (pull_request) Has been skipped
2026-08-14 08:28:49 +00:00
timmy da45cc36a3 Batch-plan mobile Search results into Today (#810)
CI / lint (push) Successful in 1m39s
CI / build-release (push) Successful in 5s
CI / release-candidate (push) Successful in 6s
2026-08-14 08:08:45 +00:00
35 changed files with 2937 additions and 209 deletions

No files matched your search

+21 -9
View File
@@ -24,19 +24,25 @@ For online delivery, the screenshot uploads before the comment is posted—to th
failures keep both the typed comment and removable preview available for retry. Offline screenshot comments
admit their text and image bytes to IndexedDB before confirmation, keep only bounded metadata in
localStorage, and use checkpointed upload/comment identities so reconnect retries cannot duplicate
either stage. The mobile **New issue** capture-first stage accepts the same image formats before a
repository is chosen. **Save to Drafts** durably writes the optimized Blob to IndexedDB before
confirmation, keeps only account-bound attachment metadata in localStorage, and restores the exact
preview when the operator later chooses a repository. The source Draft remains available until its
screenshot has safely transferred to the issue outbox; discard and bounded pruning remove the Blob.
Repository-aware durable admission likewise stores the screenshot with its account-bound outbox
either stage. The mobile **New issue** capture-first stage accepts an ordered evidence bundle of up to
five PNG, JPEG, or WebP screenshots before a repository is chosen, optimizing each image independently
to the 2 MB boundary. **Save to Drafts** durably writes every optimized Blob to IndexedDB before
confirmation, keeps only account-bound attachment metadata in localStorage, and restores the ordered
bundle when the operator later chooses a repository. A scrollable thumbnail tray lets the operator
review every restored image before filing; **Move earlier**, **Move later**, and **Remove selected**
change the durable evidence order without changing the issue title or note. The active screenshot's
optional **Evidence note** stays paired with that image through reorder, Draft restore, offline delivery,
and retry, then appears as a Markdown-safe caption immediately before its uploaded image. The selected screenshot can be cropped, privacy-redacted, highlighted, and marked with touch-drawn arrows before a flattened derivative replaces it; undo, reset, and cancel keep editing reversible without changing its note or bundle position. The source Draft remains
available until its evidence has safely transferred to the issue outbox; discard and bounded pruning remove every Blob.
Repository-aware durable admission likewise stores the evidence bundle with its account-bound outbox
capture, avoiding base64 quota pressure and synchronous multi-megabyte writes. Online and background
delivery send the original bytes as multipart form data, avoiding the roughly 33% base64 wire
expansion. Existing queued base64 screenshot payloads remain readable and are converted only at
delivery time.
Delivery creates the issue exactly once, then uploads and comments with
the image; after a partial failure, retry resumes with the confirmed issue instead of
creating a duplicate.
Delivery creates the issue exactly once, then uploads each image under a checkpointed per-image
identity and posts one ordered Markdown evidence comment. After a partial failure, retry resumes with the confirmed issue and from
the first unconfirmed image instead of duplicating the issue or earlier uploads. The installed PWA
Share Target accepts the same bounded multi-image bundle through sign-in continuation.
Pull-request replies and mobile My Work issue and PR comments use Gitea's
issue-comment API. In issue, pull-request, and unread-update conversations, typing
at least two characters after `@` offers repository-scoped teammate suggestions;
@@ -68,6 +74,12 @@ Today or interrupting active work. Cancel and browser Back preserve the Search p
confirmation claims only when needed, syncs the Later plan across devices, and returns to the preserved
query, filters, results, and scroll position. If assignment succeeds but Later storage fails, the issue
remains recoverable in My Work and the dashboard reports the partial outcome instead of claiming success.
Named mobile Search views preserve the query, type, status, and optional repository scope. They are
bounded to 20 per confirmed account and synchronize through a revisioned SQLite collection, so another
device can reopen the exact Search with one tap while stale writes surface a conflict instead of silently
overwriting newer views. Rename and delete affect only the saved view, never Gitea work; an unavailable
sync service leaves ad-hoc Search usable. Set `STACKCHAIN_SAVED_SEARCH_DB` to override the default
`.stackchain-state/saved-searches.sqlite3` path.
Search previews also
let operators assign an eligible issue and add it to Today without starting or replacing active work.
The queue action keeps the Search query, filters, results, and scroll position available for continued
+36 -10
View File
@@ -91,11 +91,18 @@ function createIssueSyncStore({
}
continue;
}
const preservedBundle = current.operationId === replacement.operationId &&
current.attachments?.every(value => value?.data || value?.blob) &&
replacement.attachments?.every(value => value?.stored && !value.data && !value.blob)
? current.attachments : null;
if (current.operationId === replacement.operationId &&
(current.attachment?.data || current.attachment?.blob) &&
replacement.attachment?.stored &&
!replacement.attachment.data && !replacement.attachment.blob) {
replacement = { ...replacement, attachment: current.attachment };
!replacement.attachment.data && !replacement.attachment.blob || preservedBundle) {
replacement = {
...replacement,
...(preservedBundle ? {attachments:preservedBundle} : {attachment:current.attachment}),
};
incoming.set(current.id, replacement);
}
if ((current.status === 'sending' && Number(current.claimUntil) > Number(now())) ||
@@ -466,6 +473,13 @@ function createBackgroundIssueSync({
return String(operationId || '').slice(0, 128 - suffix.length) + suffix;
}
function evidenceMarkdown(attachment, markdown, index) {
const note = String(attachment?.note || '').replace(/\s+/g, ' ').trim().slice(0, 240);
if (!note) return markdown;
const escaped = note.replace(/([\\`*_[\]{}()<>#+\-.!|])/g, '\\$1');
return '**Screenshot ' + (index + 1) + ' — ' + escaped + '**\n\n' + markdown;
}
async function deliverReplyRead(item) {
let current = item;
if (!current.replyConfirmed) {
@@ -525,8 +539,11 @@ function createBackgroundIssueSync({
deliveredIssue = await requestStage(item, request.url, request.options);
await checkpointClaim(item, current => ({ ...current, deliveredIssue }));
}
let attachmentMarkdown = item.attachmentMarkdown;
if (!attachmentMarkdown) {
const attachments = Array.isArray(item.attachments) ? item.attachments : [item.attachment];
const attachmentMarkdowns = Array.isArray(item.attachmentMarkdowns)
? item.attachmentMarkdowns.slice(0, attachments.length)
: (item.attachmentMarkdown ? [item.attachmentMarkdown] : []);
for (let index = attachmentMarkdowns.length; index < attachments.length; index += 1) {
const uploaded = await requestStage(
item,
base + 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(deliveredIssue.number) + '/attachments',
@@ -534,19 +551,27 @@ function createBackgroundIssueSync({
method: 'POST',
headers: {
Accept: 'application/json',
'Idempotency-Key': stageOperationId(item.operationId, 'attachment'),
'Idempotency-Key': stageOperationId(
item.operationId, attachments.length === 1 ? 'attachment' : 'attachment-' + index,
),
},
body: attachmentMultipart(item.attachment),
body: attachmentMultipart(attachments[index]),
},
);
attachmentMarkdown = String(uploaded?.markdown || '');
if (!attachmentMarkdown) {
const markdown = String(uploaded?.markdown || '');
if (!markdown) {
const error = new Error('The server did not confirm the screenshot upload.');
error.status = 422;
throw error;
}
await checkpointClaim(item, current => ({ ...current, deliveredIssue, attachmentMarkdown }));
attachmentMarkdowns.push(markdown);
await checkpointClaim(item, current => ({
...current, deliveredIssue, attachmentMarkdowns:attachmentMarkdowns.slice(),
...(attachments.length === 1 ? {attachmentMarkdown:markdown} : {}),
}));
}
const attachmentMarkdown = attachmentMarkdowns.map((markdown, index) =>
evidenceMarkdown(attachments[index], markdown, index)).join('\n\n');
await requestStage(
item,
base + 'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(deliveredIssue.number) + '/comments',
@@ -638,7 +663,8 @@ function createBackgroundIssueSync({
item.kind === 'update-reply' && item.attachment ? await deliverUpdateScreenshotReply(item) :
item.attachment && ['issue-comment', 'pull-comment'].includes(item.kind) ?
await deliverScreenshotComment(item) : item.attachment && !item.kind ?
await deliverIssueCapture(item) : await requestStage(item, request.url, request.options);
await deliverIssueCapture(item) : item.attachments?.length && !item.kind ?
await deliverIssueCapture(item) : await requestStage(item, request.url, request.options);
if (item.kind === 'issue-close' && delivered?.state !== 'closed') {
const error = new Error('Issue closure was not confirmed.');
error.status = 422;
+5 -4
View File
@@ -8,6 +8,7 @@ function createBatchFindWork({
storage = typeof localStorage === 'undefined' ? null : localStorage,
owner = () => '',
journalName = 'find-work-batch',
queueFailureReason = 'assigned but Today sync is unavailable',
autoMount = true,
}) {
let request = null;
@@ -58,7 +59,7 @@ function createBatchFindWork({
entry.state = 'assigned';
writeJournal(journal);
}
const queueResult = await queue(confirmed);
const queueResult = await queue(confirmed, journal.context);
if (queueResult === 'queued' || queueResult === 'exists') {
queued.push(key(item));
entry.state = 'queued';
@@ -67,7 +68,7 @@ function createBatchFindWork({
}
writeJournal(journal);
} else {
failed.push({ key: key(item), reason: 'assigned but Today sync is unavailable', assigned: true });
failed.push({ key: key(item), reason: queueFailureReason, assigned: true });
}
} catch (error) {
failed.push({ key: key(item), reason: error?.message || 'assignment failed' });
@@ -81,7 +82,7 @@ function createBatchFindWork({
return outcome;
}
function run(items, estimates = {}) {
function run(items, estimates = {}, context = null) {
if (request) return request;
const selected = Array.isArray(items) ? items.slice() : [];
const available = Math.max(0, Number(capacity()) || 0);
@@ -112,7 +113,7 @@ function createBatchFindWork({
}
}
const journal = {
owner: String(owner() || ''), available,
owner: String(owner() || ''), available, context,
items: selected.map(item => ({ item, estimate: estimates[key(item)] || null, state: 'pending' })),
};
writeJournal(journal);
+53 -1
View File
@@ -121,6 +121,15 @@ textarea { resize: vertical; min-height: 120px; }
.cmd-search-scope select { min-width:0; padding:7px; border-radius:8px; border:1px solid #31577f; background:#0b1526; color:#e5e7eb; }
.cmd-search-scope input { min-width:0; padding:7px; border-radius:8px; border:1px solid #31577f; background:#0b1526; color:#e5e7eb; }
.cmd-repository-status { grid-column:2 / -1; min-height:16px; color:#93a4b8; font-size:12px; }
.saved-searches { margin-top:8px; padding:8px; border:1px solid #1f3a5f; border-radius:8px; }
.saved-search-header, .saved-search-create, .saved-search-row, .saved-search-row-actions { display:flex; align-items:center; gap:8px; }
.saved-search-header { justify-content:space-between; }
.saved-search-create { margin-top:6px; }
.saved-search-create input { flex:1; min-width:0; }
.saved-search-list { display:grid; gap:4px; margin-top:6px; }
.saved-search-row { justify-content:space-between; border-top:1px solid #1f3a5f; padding-top:4px; }
.saved-search-open { flex:1; min-width:0; text-align:left; }
.saved-search-action { min-height:44px; }
#cmd-results { margin-top:8px; max-height:min(65vh,520px); overflow-y:auto; }
.cmd-item { padding: 10px; min-height:44px; cursor: pointer; border-radius: 10px; color:#e5e7eb; display:flex; gap:10px; align-items:center; justify-content:space-between; }
.cmd-item:hover, .cmd-item.selected { background: #10233a; outline:1px solid #31577f; }
@@ -129,11 +138,27 @@ textarea { resize: vertical; min-height: 120px; }
.cmd-select-result { min-height:44px; width:100%; display:grid; grid-template-columns:28px 1fr auto; gap:10px; align-items:center; text-align:left; }
.cmd-select-result input { width:22px; height:22px; }
.cmd-select-result[disabled] { cursor:not-allowed; opacity:.62; }
.search-batch-actions { position:sticky; bottom:0; z-index:3; display:grid; grid-template-columns:1fr 1fr; gap:8px; padding:10px 0 calc(10px + env(safe-area-inset-bottom)); background:#0b1526; border-top:1px solid #2a496e; }
.search-batch-actions { position:sticky; bottom:0; z-index:3; display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; padding:10px 0 calc(10px + env(safe-area-inset-bottom)); background:#0b1526; border-top:1px solid #2a496e; }
.search-batch-actions[hidden] { display:none; }
.search-batch-actions span { grid-column:1 / -1; }
.search-batch-actions button, .search-batch-recovery { min-height:44px; }
.search-batch-recovery { width:100%; font-weight:700; }
.search-batch-estimate-review { display:grid; gap:12px; padding:12px; border:1px solid #2a496e; border-radius:12px; background:#101f36; }
.search-batch-estimate-review[hidden] { display:none; }
.search-batch-estimate-review > div:first-child, #search-batch-estimate-list { display:grid; gap:8px; }
.search-batch-estimate-row { display:grid; grid-template-columns:minmax(0,1fr) minmax(92px,auto); gap:10px; align-items:center; overflow-wrap:anywhere; }
.search-batch-estimate-row label { display:flex; align-items:center; gap:6px; }
.search-batch-estimate-review input { min-height:44px; width:76px; }
.search-batch-estimate-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; padding-bottom:env(safe-area-inset-bottom); background:#101f36; }
.search-batch-estimate-actions button { min-height:44px; }
.search-release-review { display:grid; gap:12px; max-height:calc(100dvh - 48px); overflow:auto; padding:12px; border:1px solid #2a496e; border-radius:12px; background:#101f36; overflow-wrap:anywhere; }
.search-release-review[hidden] { display:none; }
.search-release-review > div:first-child, #search-release-list, .search-release-row { display:grid; gap:6px; }
.search-release-review label { display:grid; gap:6px; }
.search-release-review select, .search-release-review input { min-height:44px; width:100%; }
.search-release-row { padding:8px 0; border-bottom:1px solid #2a496e; }
.search-release-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; padding-bottom:env(safe-area-inset-bottom); background:#101f36; }
.search-release-actions button { min-height:44px; }
.cmd-group { padding:8px 10px 3px; color:#60a5fa; font-size:11px; font-weight:700; letter-spacing:.08em; text-transform:uppercase; }
#whiteboard-modal, #markdown-modal { position: fixed; inset: 0; background: rgba(5,12,21,.55); display: none; align-items: center; justify-content: center; z-index: 40; backdrop-filter: blur(6px); }
@@ -597,6 +622,30 @@ textarea { resize: vertical; min-height: 120px; }
.create-issue-filing { display:grid; gap:12px; min-width:0; }
.create-issue-filing[hidden] { display:none; }
.create-issue-attachment { display:grid; gap:8px; min-width:0; }
#create-issue-attachment-preview { grid-template-columns:1fr; }
#create-issue-attachment-image { grid-row:auto; width:100%; height:auto; max-height:320px; }
.issue-evidence-tray { display:flex; gap:8px; max-width:100%; padding:2px 0 6px; overflow-x:auto; overscroll-behavior-inline:contain; scrollbar-width:thin; }
.issue-evidence-tray[hidden] { display:none; }
.issue-evidence-thumbnail { position:relative; flex:0 0 64px; min-width:44px; min-height:64px; padding:3px; border:2px solid transparent; border-radius:10px; background:#10213a; }
.issue-evidence-thumbnail[aria-pressed="true"] { border-color:#60a5fa; box-shadow:0 0 0 2px rgba(96,165,250,.25); }
.issue-evidence-thumbnail img { display:block; width:56px; height:56px; border-radius:6px; object-fit:cover; }
.issue-evidence-thumbnail span { position:absolute; right:3px; bottom:3px; min-width:20px; padding:1px 4px; border-radius:999px; background:#07101d; color:#fff; font-size:12px; text-align:center; }
.issue-evidence-note { display:grid; gap:6px; min-width:0; }
.issue-evidence-note textarea { box-sizing:border-box; width:100%; min-height:72px; padding:10px; resize:vertical; border:1px solid #2a496e; border-radius:8px; background:#07101d; color:#e5e7eb; font:inherit; }
.issue-evidence-note textarea:focus-visible { outline:2px solid #60a5fa; outline-offset:2px; }
.issue-evidence-review-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
.issue-evidence-review-actions button { min-width:44px; min-height:44px; }
.issue-evidence-editor { position:fixed; inset:0; z-index:70; display:grid; place-items:end center; overflow-x:hidden; background:rgba(2,6,15,.92); }
.issue-evidence-editor[hidden] { display:none; }
.issue-evidence-editor-panel { box-sizing:border-box; width:min(560px,100%); max-height:100dvh; overflow:auto; overflow-x:hidden; display:grid; gap:12px; padding:16px; padding-bottom:calc(16px + env(safe-area-inset-bottom)); background:#0b1526; border:1px solid #2a496e; border-radius:14px 14px 0 0; }
.issue-evidence-editor-panel header { display:flex; align-items:start; justify-content:space-between; gap:12px; }
.issue-evidence-editor-panel h3 { margin:0 0 4px; }
.issue-evidence-editor canvas { display:block; max-width:100%; width:100%; max-height:60dvh; object-fit:contain; touch-action:none; border:1px solid #365b86; border-radius:8px; background:#020617; }
.issue-evidence-editor-tools { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:8px; }
.issue-evidence-editor button { min-width:44px; min-height:44px; }
.issue-evidence-editor button[aria-pressed="true"] { border-color:#60a5fa; background:#173a64; color:#fff; }
.issue-evidence-editor-apply { width:100%; }
@media(max-width:320px) { .issue-evidence-editor-panel { padding:12px; } .issue-evidence-editor-tools { grid-template-columns:repeat(2,minmax(0,1fr)); } }
.create-issue-repository-more { min-height:44px; width:100%; }
.create-issue-repository-picker { min-width:0; display:grid; gap:8px; }
.create-issue-repository-picker input { min-width:0; min-height:44px; width:100%; padding:8px; border-radius:8px; border:1px solid #1f3a5f; background:#0b1526; color:#e5e7eb; }
@@ -717,6 +766,9 @@ textarea { resize: vertical; min-height: 120px; }
.cmd-search-scope { grid-template-columns:auto minmax(0,1fr); }
#cmd-search-kind, #cmd-search-state { min-height:44px; width:100%; }
#cmd-search-repository { min-height:44px; width:100%; }
.saved-search-create { align-items:stretch; }
.saved-search-create input, .saved-search-open, .saved-search-row-actions button { min-height:44px; }
.saved-search-row { align-items:stretch; }
#cmd-results { flex:1; min-height:0; overflow-y:auto; max-height:none; overscroll-behavior:contain; padding-bottom:env(safe-area-inset-bottom); }
.create-issue-panel { width:100%; border-left:0; padding:14px; }
.pull-sheet-panel { width:100%; border-left:0; padding:14px; }
+34 -6
View File
@@ -479,9 +479,30 @@
image: qs('#create-issue-attachment-image'),
meta: qs('#create-issue-attachment-meta'),
remove: qs('#remove-create-issue-attachment'),
tray: qs('#create-issue-evidence-tray'),
earlier: qs('#move-create-issue-attachment-earlier'),
later: qs('#move-create-issue-attachment-later'),
note: qs('#create-issue-evidence-note'),
noteLabel: qs('#create-issue-evidence-note-label'),
status: qs('#create-issue-attachment-status'),
readyMessage: 'Screenshot ready to file with this issue.',
removedMessage: 'Screenshot removed. Your issue draft is unchanged.',
editor: {
document,
edit: qs('#edit-create-issue-attachment'),
dialog: qs('#issue-evidence-editor'),
canvas: qs('#issue-evidence-editor-canvas'),
exportCanvas: qs('#issue-evidence-editor-export'),
crop: qs('#crop-issue-evidence'),
redact: qs('#redact-issue-evidence'),
highlight: qs('#highlight-issue-evidence'),
arrow: qs('#arrow-issue-evidence'),
undo: qs('#undo-issue-evidence-edit'),
reset: qs('#reset-issue-evidence-edit'),
cancel: qs('#cancel-issue-evidence-edit'),
apply: qs('#apply-issue-evidence-edit'),
status: qs('#issue-evidence-editor-status'),
},
createObjectURL: file => URL.createObjectURL(file),
revokeObjectURL: url => URL.revokeObjectURL(url),
readDataUrl: file => new Promise((resolve, reject) => {
@@ -2652,7 +2673,9 @@
editingOutboxId = hydrated.id;
issueCapture.saveDraft(hydrated);
openCreateIssueSheet();
if (hydrated.attachment) createIssueAttachmentController.restore(hydrated.attachment);
if (hydrated.attachments || hydrated.attachment) {
createIssueAttachmentController.restore(hydrated.attachments || hydrated.attachment);
}
else createIssueAttachmentController.clear();
qs('#create-issue-status').textContent = 'Edit this queued issue, then send again.';
} catch (error) {
@@ -4424,8 +4447,8 @@
});
searchBatchPlanning = mountSearchBatchPlanning(
document, createBatchFindWork, todayWork, ()=>planningOwnerLogin, fetchReviewJson,
searchPreviewPath, queueToday, acceptClaimedIssue, index=>commandItems[index]?.result,
()=>renderCommands(qs('#cmd-input').value), escapeHtml, escAttr
searchPreviewPath, queueToday, todaySync, acceptClaimedIssue, i=>commandItems[i]?.result,
()=>renderCommands(qs('#cmd-input').value), escapeHtml, escAttr, laterWork, laterPicker
);
searchDefer = createSearchDefer({
claim: detail => searchPreview.claim(detail),
@@ -4613,6 +4636,9 @@
},
});
taskOverlayHistory.start();
createSavedSearches.mount(
document, fetch, commandSearch, applySearchScope, taskOverlayHistory
).load();
qs('#open-palette').addEventListener('click', openCommandPalette);
qs('#close-command-palette').addEventListener('click', () => taskOverlayHistory.close());
qs('#cmd-load-more').addEventListener('click', () => commandSearch.loadMore());
@@ -4932,10 +4958,11 @@
});
qs('#save-unfiled-issue').addEventListener('click', async () => {
try {
const evidence = await createIssueAttachmentController.serialize();
const captureDraft = {
title: qs('#create-issue-title').value.trim(),
body: qs('#create-issue-body').value.trim(),
attachment: await createIssueAttachmentController.serialize(),
...(Array.isArray(evidence) ? {attachments:evidence} : {attachment:evidence}),
};
if (showDraftCapacityDialog(unfiledCaptures)) return;
const savedCapture = await unfiledCaptures.save(captureDraft);
@@ -5086,9 +5113,10 @@
qs('#create-issue-status').textContent = createAndStartRequested ?
'Creating issue and adding it to Today…' : 'Saving for background delivery…';
try {
const evidence = await createIssueAttachmentController.serialize();
const durableDraft = {
...captureDraft,
attachment: await createIssueAttachmentController.serialize(),
...(Array.isArray(evidence) ? {attachments:evidence} : {attachment:evidence}),
...(rUC ? { sourceCaptureId: rUC } : {}),
...(createAndStartRequested ? { completionIntent: 'create-and-start' } : {}),
};
@@ -5101,7 +5129,7 @@
await issueOutbox.enqueueDurably(durableDraft));
const queued = admission.item;
const fS = dFS.current();
if (rUC && (!durableDraft.attachment || admission.background)) {
if (rUC && ((!durableDraft.attachment && !durableDraft.attachments) || admission.background)) {
await unfiledCaptures.completeResume(rUC);
rUC = '';
}
+74 -4
View File
@@ -451,6 +451,18 @@
<datalist id="cmd-search-repositories"></datalist>
<span id="cmd-repository-status" class="cmd-repository-status" aria-live="polite"></span>
</fieldset>
<section class="saved-searches" aria-labelledby="saved-searches-heading">
<div class="saved-search-header">
<strong id="saved-searches-heading">Saved searches</strong>
<span id="saved-search-status" class="small" aria-live="polite"></span>
</div>
<div class="saved-search-create">
<label for="saved-search-name" class="sr-only">Saved search name</label>
<input id="saved-search-name" type="text" maxlength="60" autocomplete="off" placeholder="Name this search" />
<button id="save-current-search" class="saved-search-action" type="button">Save search</button>
</div>
<div id="saved-search-list" class="saved-search-list" aria-label="Saved searches"></div>
</section>
<div id="cmd-search-action-status" class="small" aria-live="polite"></div>
<button id="resume-search-batch" class="search-batch-recovery" type="button" hidden>Resume batch</button>
<div id="cmd-results" class="stack" role="listbox" aria-label="Commands and work search results"></div>
@@ -458,8 +470,33 @@
<div class="search-batch-actions" id="search-batch-actions" hidden>
<span id="search-selection-status" class="small" aria-live="polite">No issues selected.</span>
<button id="cancel-search-selection" type="button">Cancel</button>
<button id="defer-selected-search-results" type="button" disabled>Defer</button>
<button id="plan-selected-search-results" type="button" disabled>Plan release</button>
<button id="queue-selected-search-results" type="button" disabled>Assign &amp; add to Today</button>
</div>
<section class="search-batch-estimate-review" id="search-batch-estimate-review"
aria-labelledby="search-batch-estimate-heading" hidden>
<div><strong id="search-batch-estimate-heading">Fit this work into Today</strong>
<span class="small" id="search-batch-estimate-summary" aria-live="polite"></span></div>
<div id="search-batch-estimate-list"></div>
<div class="search-batch-estimate-actions">
<button id="cancel-search-batch-estimates" type="button">Back</button>
<button id="confirm-search-batch-estimates" type="button">Confirm &amp; assign</button>
</div>
</section>
<section class="search-release-review" id="search-release-review"
aria-labelledby="search-release-heading" hidden>
<div><strong id="search-release-heading">Plan selected issues into a release</strong>
<span class="small" id="search-release-summary" aria-live="polite"></span></div>
<label>Open milestone<select id="search-release-milestone" required></select></label>
<label>Shared due date <span class="small">(optional)</span>
<input id="search-release-due-date" type="date" /></label>
<div id="search-release-list"></div>
<div class="search-release-actions">
<button id="cancel-search-release" type="button">Back</button>
<button id="confirm-search-release" type="button">Assign &amp; plan</button>
</div>
</section>
</div>
<div class="search-preview" id="search-preview" role="dialog" aria-modal="true" aria-labelledby="search-preview-title">
@@ -717,15 +754,25 @@
<button id="file-new-issue" type="button">File now</button>
</div>
<section class="create-issue-attachment" aria-labelledby="create-issue-attachment-label">
<strong id="create-issue-attachment-label">Screenshot <span class="small">Optional · PNG, JPEG, or WebP · 2 MB max</span></strong>
<strong id="create-issue-attachment-label">Evidence screenshots <span class="small">Optional · Up to 5 · PNG, JPEG, or WebP · 2 MB each</span></strong>
<div class="issue-attachment-controls">
<label class="issue-attachment-trigger" for="create-issue-attachment">Attach screenshot</label>
<input class="visually-hidden" id="create-issue-attachment" type="file" accept="image/png,image/jpeg,image/webp" />
<label class="issue-attachment-trigger" for="create-issue-attachment">Add screenshots</label>
<input class="visually-hidden" id="create-issue-attachment" type="file" accept="image/png,image/jpeg,image/webp" multiple />
</div>
<div class="issue-attachment-preview" id="create-issue-attachment-preview" hidden>
<img id="create-issue-attachment-image" alt="Selected screenshot preview" />
<span class="small" id="create-issue-attachment-meta"></span>
<button id="remove-create-issue-attachment" type="button">Remove</button>
<div class="issue-evidence-tray" id="create-issue-evidence-tray" role="toolbar" aria-label="Evidence screenshots" hidden></div>
<label class="issue-evidence-note" for="create-issue-evidence-note">
<span id="create-issue-evidence-note-label">Evidence note (optional)</span>
<textarea id="create-issue-evidence-note" maxlength="240" rows="2" disabled placeholder="What does this screenshot show?"></textarea>
</label>
<div class="issue-evidence-review-actions" aria-label="Reorder selected screenshot">
<button id="move-create-issue-attachment-earlier" type="button">Move earlier</button>
<button id="edit-create-issue-attachment" type="button">Edit screenshot</button>
<button id="remove-create-issue-attachment" type="button">Remove selected</button>
<button id="move-create-issue-attachment-later" type="button">Move later</button>
</div>
</div>
<div class="small" id="create-issue-attachment-status" aria-live="polite"></div>
</section>
@@ -780,6 +827,26 @@
<div id="create-issue-capture-status" class="small" aria-live="assertive"></div>
</form>
</section>
<section class="issue-evidence-editor" id="issue-evidence-editor" role="dialog" aria-modal="true" aria-labelledby="issue-evidence-editor-heading" hidden>
<div class="issue-evidence-editor-panel">
<header>
<div><h3 id="issue-evidence-editor-heading">Edit screenshot evidence</h3><span class="small">Edits stay on this device until you file.</span></div>
<button id="cancel-issue-evidence-edit" type="button">Cancel</button>
</header>
<canvas id="issue-evidence-editor-canvas" role="img" aria-label="Screenshot editing canvas. Drag to crop, redact, highlight, or point with an arrow."></canvas>
<canvas id="issue-evidence-editor-export" hidden></canvas>
<div class="issue-evidence-editor-tools" role="toolbar" aria-label="Screenshot editing tools">
<button id="crop-issue-evidence" type="button" aria-pressed="false">Crop</button>
<button id="redact-issue-evidence" type="button" aria-pressed="true">Redact</button>
<button id="highlight-issue-evidence" type="button" aria-pressed="false">Highlight</button>
<button id="arrow-issue-evidence" type="button" aria-pressed="false">Arrow</button>
<button id="undo-issue-evidence-edit" type="button">Undo</button>
<button id="reset-issue-evidence-edit" type="button">Reset</button>
</div>
<div class="small" id="issue-evidence-editor-status" aria-live="polite">Drag over private information to hide it.</div>
<button class="issue-evidence-editor-apply" id="apply-issue-evidence-edit" type="button">Apply flattened edit</button>
</div>
</section>
</div>
<div class="draft-capacity-sheet" id="draft-capacity-sheet" role="dialog" aria-modal="true" aria-labelledby="draft-capacity-heading" hidden>
@@ -1082,6 +1149,7 @@
<script src="static/security-center.js"></script>
<script src="static/markdown.js"></script>
<script src="static/commands.js"></script>
<script src="static/saved-searches.js"></script>
<script src="static/search-preview.js"></script>
<script src="static/search-defer.js"></script>
<script src="static/widgets.js"></script>
@@ -1129,6 +1197,8 @@
<script src="static/search-batch-plan.js"></script>
<script src="static/conversation.js"></script>
<script src="static/comment-actions.js"></script>
<script src="static/issue-evidence-review.js"></script>
<script src="static/issue-evidence-editor.js"></script>
<script src="static/issue-attachment.js"></script>
<script src="static/issue-sheet.js"></script>
<script src="static/create-issue-sheet.js"></script>
+230 -109
View File
@@ -1,55 +1,27 @@
(function(root, factory) {
const api = factory();
const review = typeof module === 'object' && module.exports ? require('./issue-evidence-review.js') : root.issueEvidenceReview;
const editor = typeof module === 'object' && module.exports ? require('./issue-evidence-editor.js') : root.issueEvidenceEditor;
const api = factory(review, editor);
if (typeof module === 'object' && module.exports) module.exports = api;
else root.issueAttachment = api;
})(typeof self !== 'undefined' ? self : this, function() {
})(typeof self !== 'undefined' ? self : this, function(issueEvidenceReview, issueEvidenceEditor) {
'use strict';
const MAX_BYTES = 2 * 1024 * 1024;
const MAX_FILES = 5;
const MAX_FILES_MESSAGE = 'Up to 5 screenshots. Remove one before adding another.';
const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
function namedBlob(blob, name) {
if (typeof File === 'function') {
return new File([blob], name, { type: blob.type });
}
Object.defineProperty(blob, 'name', { value: name, configurable: true });
return blob;
function normalizeNote(value) {
return String(value || '').replace(/\s+/g, ' ').trim().slice(0, 240);
}
async function optimizeImage(file, environment = {}) {
if (file.size <= MAX_BYTES) return file;
const decode = environment.createImageBitmap || globalThis.createImageBitmap;
const makeCanvas = environment.createCanvas || (() => document.createElement('canvas'));
if (typeof decode !== 'function') {
throw new Error('This browser cannot optimize the screenshot. Try cropping it and choose it again.');
}
let bitmap;
try {
bitmap = await decode(file);
const canvas = makeCanvas();
const context = canvas && canvas.getContext && canvas.getContext('2d');
if (!context || !bitmap.width || !bitmap.height) throw new Error('decode');
let scale = Math.min(1, Math.sqrt(MAX_BYTES / file.size) * 0.92);
for (let attempt = 0; attempt < 10; attempt += 1) {
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
const blob = await new Promise(resolve => {
canvas.toBlob(resolve, file.type, file.type === 'image/png' ? undefined : 0.86);
});
if (!blob) throw new Error('encode');
if (blob.size > 0 && blob.size <= MAX_BYTES) return namedBlob(blob, file.name);
scale *= 0.8;
}
} catch (_error) {
throw new Error('The screenshot could not be optimized. Try cropping it and choose it again.');
} finally {
if (bitmap && typeof bitmap.close === 'function') bitmap.close();
}
throw new Error('The screenshot could not be optimized below 2 MB. Try cropping it and choose it again.');
function escapeMarkdown(value) {
return value.replace(/([\\`*_[\]{}()<>#+\-.!|])/g, '\\$1');
}
const optimizeImage = issueEvidenceReview.optimizeImage;
function multipart(attachment) {
let blob = attachment?.blob;
if (!blob && attachment?.data) {
@@ -65,6 +37,7 @@
function create(options) {
const upload = options.upload;
const maxFiles = options.maxFiles === MAX_FILES ? MAX_FILES : 1;
const optimizeSelectedImage = options.optimizeImage || optimizeImage;
const createOperationId = options.createOperationId || (() => {
if (typeof globalThis !== 'undefined' && globalThis.crypto?.randomUUID) {
@@ -72,10 +45,7 @@
}
return Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
});
let selected = null;
let confirmed = null;
let serialized = null;
let operationId = null;
let selected = [];
let selectionGeneration = 0;
function commitSelection(file) {
@@ -83,14 +53,18 @@
file.size <= 0 || file.size > MAX_BYTES) {
throw new Error('The screenshot could not be optimized below 2 MB. Try cropping it and choose it again.');
}
selected = file;
confirmed = null;
serialized = null;
operationId = createOperationId();
if (selected.length >= maxFiles) {
if (maxFiles === 1) selected = [];
else throw new Error(MAX_FILES_MESSAGE);
}
selected.push({file, note:'', confirmed:null, serialized:null, operationId:createOperationId()});
return state();
}
function select(file) {
if (selected.length >= maxFiles && maxFiles > 1) {
throw new Error(MAX_FILES_MESSAGE);
}
const generation = ++selectionGeneration;
if (!file || !IMAGE_TYPES.has(file.type)) {
throw new Error('Choose a PNG, JPEG, or WebP screenshot.');
@@ -109,87 +83,166 @@
function clear() {
selectionGeneration += 1;
selected = null;
confirmed = null;
serialized = null;
operationId = null;
selected = [];
}
function remove(index) {
const position = Number(index);
if (!Number.isInteger(position) || position < 0 || position >= selected.length) return state();
selectionGeneration += 1;
selected.splice(position, 1);
return state();
}
function move(fromIndex, toIndex) {
const from = Number(fromIndex);
const to = Number(toIndex);
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 0 ||
from >= selected.length || to < 0 || to >= selected.length || from === to) return state();
const [item] = selected.splice(from, 1);
selected.splice(to, 0, item);
return state();
}
function replace(index, file) {
const position = Number(index);
if (!Number.isInteger(position) || position < 0 || position >= selected.length) return state();
if (!file || !IMAGE_TYPES.has(file.type) || !Number.isFinite(file.size) ||
file.size <= 0 || file.size > MAX_BYTES) {
throw new Error('The edited screenshot must be a PNG, JPEG, or WebP image no larger than 2 MB.');
}
selectionGeneration += 1;
selected[position] = {
...selected[position], file, confirmed:null, serialized:null, operationId:createOperationId(),
};
return state();
}
function setNote(index, value) {
const position = Number(index);
if (!Number.isInteger(position) || position < 0 || position >= selected.length) return state();
selected[position].note = normalizeNote(value);
selected[position].serialized = null;
return state();
}
function note(index) {
const position = Number(index);
return Number.isInteger(position) && selected[position] ? selected[position].note : '';
}
function restore(value) {
if (Array.isArray(value)) {
clear();
if (value.length > maxFiles) throw new Error(MAX_FILES_MESSAGE);
value.forEach(attachment => restoreOne(attachment));
return state();
}
clear();
restoreOne(value);
return state();
}
function restoreOne(value) {
const contentType = String(value?.contentType || '');
const filename = String(value?.filename || '');
const blob = value?.blob;
const data = String(value?.data || '');
if (!blob && !data) {
clear();
throw new Error('The saved screenshot is unavailable. Retry before editing this issue.');
}
const padding = (data.match(/=*$/) || [''])[0].length;
const size = blob ? Number(blob.size) : Math.max(1, Math.floor(data.length * 3 / 4) - padding);
select({ name: filename, type: contentType, size, ...(blob ? { blob } : {}) });
serialized = blob ? { filename, contentType, blob } : { filename, contentType, data };
return state();
commitSelection({ name: filename, type: contentType, size, ...(blob ? { blob } : {}) });
const item = selected[selected.length - 1];
item.note = normalizeNote(value?.note);
item.serialized = {
...(blob ? { filename, contentType, blob } : { filename, contentType, data }),
...(item.note ? {note:item.note} : {}),
};
}
function state() {
return selected ? {
name: selected.name,
size: selected.size,
uploaded: Boolean(confirmed),
} : null;
const values = selected.map(item => ({
name: item.file.name,
size: item.file.size,
uploaded: Boolean(item.confirmed),
}));
return values.length > 1 ? values : (values[0] || null);
}
function serializeItem(item) {
if (!item.serialized) item.serialized = {
filename:item.file.name, contentType:item.file.type, blob:item.file.blob || item.file,
...(item.note ? {note:item.note} : {}),
};
return { ...item.serialized };
}
async function serialize() {
if (!selected) return null;
if (!serialized) {
serialized = {
filename: selected.name,
contentType: selected.type,
blob: selected.blob || selected,
};
}
return { ...serialized };
if (!selected.length) return null;
const values = selected.map(serializeItem);
return values.length > 1 ? values : values[0];
}
async function prepareComment(item, body) {
async function prepareComment(target, body) {
const text = String(body || '').trim();
if (!selected) return text;
if (!confirmed) {
const attachment = await serialize();
confirmed = await upload({
repository: item.repository,
number: item.number,
filename: attachment.filename,
content_type: attachment.contentType,
...(attachment.blob ? { blob: attachment.blob } : { data: attachment.data }),
operation_id: operationId,
});
if (!confirmed || typeof confirmed.markdown !== 'string' || !confirmed.markdown) {
confirmed = null;
throw new Error('The server did not confirm the screenshot upload.');
if (!selected.length) return text;
const markdown = [];
for (const evidence of selected) {
if (!evidence.confirmed) {
const attachment = serializeItem(evidence);
evidence.confirmed = await upload({
repository: target.repository,
number: target.number,
filename: attachment.filename,
content_type: attachment.contentType,
...(attachment.blob ? { blob: attachment.blob } : { data: attachment.data }),
operation_id: evidence.operationId,
});
if (!evidence.confirmed || typeof evidence.confirmed.markdown !== 'string' || !evidence.confirmed.markdown) {
evidence.confirmed = null;
throw new Error('The server did not confirm the screenshot upload.');
}
}
if (evidence.note) {
markdown.push('**Screenshot ' + (markdown.length + 1) + ' — ' + escapeMarkdown(evidence.note) + '**\n\n' +
evidence.confirmed.markdown);
} else markdown.push(evidence.confirmed.markdown);
}
return text ? text + '\n\n' + confirmed.markdown : confirmed.markdown;
const evidence = markdown.join('\n\n');
return text ? text + '\n\n' + evidence : evidence;
}
return { select, restore, clear, state, serialize, prepareComment };
return { select, restore, remove, move, replace, setNote, note, clear, state, serialize, prepareComment };
}
function mount(options) {
const controller = create(options);
const controller = create({
...options, maxFiles:options.maxFiles || (options.input?.multiple ? MAX_FILES : 1),
});
const clearSelection = controller.clear;
const restoreSelection = controller.restore;
const reviewEnabled = Boolean(options.tray && options.earlier && options.later);
let previewUrl = '';
let selectionSequence = 0;
const review = reviewEnabled ? issueEvidenceReview.create({
...options, edit:options.editor?.edit, controller,
}) : null;
function setBusy(busy) {
options.input.disabled = Boolean(busy);
options.remove.disabled = Boolean(busy);
function setBusy(value) {
options.input.disabled = Boolean(value);
options.remove.disabled = Boolean(value);
if (options.editor?.edit) options.editor.edit.disabled = Boolean(value) || !controller.state();
review?.setBusy(value);
}
function clearPreview() {
selectionSequence += 1;
if (previewUrl) options.revokeObjectURL(previewUrl);
previewUrl = '';
review?.clear();
if (options.editor?.edit) options.editor.edit.disabled = true;
options.image.src = '';
options.preview.hidden = true;
options.input.value = '';
@@ -203,29 +256,53 @@
options.image.src = previewUrl;
options.meta.textContent = file.name + ' · ' + Math.ceil(file.size / 1024) + ' KB';
options.preview.hidden = false;
if (options.editor?.edit) options.editor.edit.disabled = false;
options.status.textContent = optimized ? 'Screenshot optimized and ready to upload.' :
(options.readyMessage || 'Screenshot ready to upload with this comment.');
}
options.input.addEventListener('change', event => {
const file = event.target.files && event.target.files[0];
const files = Array.from(event.target.files || []);
const sequence = ++selectionSequence;
let result;
try {
result = controller.select(file);
} catch (error) {
if (!files.length) return;
let first;
try { first = controller.select(files[0]); }
catch (error) {
options.status.textContent = error.message;
options.input.value = '';
return;
}
if (!result || typeof result.then !== 'function') {
showPreview(file, false);
if (!reviewEnabled && files.length === 1 && (!first || typeof first.then !== 'function')) {
showPreview(files[0], false);
return;
}
options.status.textContent = 'Optimizing screenshot…';
options.input.disabled = true;
return result.then(() => controller.serialize()).then(value => {
if (sequence === selectionSequence) showPreview(value.blob, true);
let optimized = Boolean(first && typeof first.then === 'function');
if (optimized) {
options.status.textContent = 'Optimizing screenshot…';
options.input.disabled = true;
}
const selectAll = files.slice(1).reduce((pending, file) => pending.then(async () => {
const result = controller.select(file);
if (result && typeof result.then === 'function') {
optimized = true;
options.status.textContent = 'Optimizing screenshot…';
options.input.disabled = true;
await result;
}
}), Promise.resolve(first));
return selectAll.then(() => controller.serialize()).then(value => {
if (sequence !== selectionSequence) return;
const values = Array.isArray(value) ? value : [value];
const latest = values[values.length - 1];
if (reviewEnabled) {
review.render(values, values.length - 1, optimized);
} else {
showPreview(latest.blob, optimized);
if (values.length > 1) {
options.meta.textContent = values.length + ' screenshots ready · latest: ' + latest.filename;
options.status.textContent = values.length + ' screenshots ready to file in this order.';
}
}
}).catch(error => {
if (sequence === selectionSequence) {
options.status.textContent = error.message;
@@ -236,22 +313,66 @@
});
});
options.remove.addEventListener('click', () => {
clearPreview();
options.status.textContent = options.removedMessage || 'Screenshot removed. Your comment is unchanged.';
const current = controller.state();
const count = Array.isArray(current) ? current.length : (current ? 1 : 0);
if (count <= 1) {
clearPreview();
options.status.textContent = options.removedMessage || 'Screenshot removed. Your comment is unchanged.';
return Promise.resolve();
}
const removedIndex = reviewEnabled ? review.activeIndex() : count - 1;
controller.remove(removedIndex);
selectionSequence += 1;
review?.afterRemoval(removedIndex, count);
return controller.serialize().then(value => {
const values = Array.isArray(value) ? value : [value];
if (reviewEnabled) {
review.render(values, review.activeIndex());
} else {
const latest = values[values.length - 1];
showPreview(latest.blob, false);
options.meta.textContent = values.length + ' screenshots ready · latest: ' + latest.filename;
}
options.status.textContent = options.removedMessage || 'Latest screenshot removed. Your text is unchanged.';
});
});
function restorePreview(value) {
clearPreview();
const restored = controller.restore(value);
previewUrl = value.blob ? options.createObjectURL(value.blob) :
'data:' + value.contentType + ';base64,' + value.data;
const restored = restoreSelection(value);
const values = Array.isArray(value) ? value : [value];
if (reviewEnabled) {
review.render(values, values.length - 1);
return restored;
}
const latest = values[values.length - 1];
previewUrl = latest.blob ? options.createObjectURL(latest.blob) :
'data:' + latest.contentType + ';base64,' + latest.data;
options.image.src = previewUrl;
options.meta.textContent = restored.name + ' · ' + Math.ceil(restored.size / 1024) + ' KB';
options.meta.textContent = values.length > 1 ?
values.length + ' screenshots ready · latest: ' + latest.filename :
restored.name + ' · ' + Math.ceil(restored.size / 1024) + ' KB';
options.preview.hidden = false;
options.status.textContent = options.readyMessage || 'Screenshot ready to upload with this comment.';
options.status.textContent = values.length > 1 ?
values.length + ' screenshots ready to file in this order.' :
(options.readyMessage || 'Screenshot ready to upload with this comment.');
return restored;
}
if (review && options.editor && issueEvidenceEditor) {
issueEvidenceEditor.mount({
...options.editor,
controller,
getActiveIndex:review.activeIndex,
optimizeImage,
onApplied: async index => {
const value = await controller.serialize();
review.render(value, index);
options.status.textContent = 'Edited screenshot flattened and ready to file.';
},
});
options.editor.edit.disabled = !controller.state();
}
return Object.assign(controller, { clear: clearPreview, restore: restorePreview, setBusy });
}
+305
View File
@@ -0,0 +1,305 @@
(function(root, factory) {
const api = factory();
if (typeof module === 'object' && module.exports) module.exports = api;
else root.issueEvidenceEditor = api;
})(typeof self !== 'undefined' ? self : this, function() {
'use strict';
function boundedRect(value, bounds) {
const x = Math.max(bounds.x, Math.min(bounds.x + bounds.width - 1, Math.round(Number(value.x) || 0)));
const y = Math.max(bounds.y, Math.min(bounds.y + bounds.height - 1, Math.round(Number(value.y) || 0)));
const width = Math.max(1, Math.min(bounds.x + bounds.width - x, Math.round(Number(value.width) || 0)));
const height = Math.max(1, Math.min(bounds.y + bounds.height - y, Math.round(Number(value.height) || 0)));
return { x, y, width, height };
}
function boundedPoint(value, bounds) {
return {
x: Math.max(bounds.x, Math.min(bounds.x + bounds.width, Math.round(Number(value.x) || 0))),
y: Math.max(bounds.y, Math.min(bounds.y + bounds.height, Math.round(Number(value.y) || 0))),
};
}
function createModel(size) {
const full = { x:0, y:0, width:Math.max(1, Math.round(size.width)), height:Math.max(1, Math.round(size.height)) };
let crop = { ...full };
let redactions = [];
let annotations = [];
let history = [];
function remember() {
history.push({
crop:{...crop}, redactions:redactions.map(value => ({...value})),
annotations:annotations.map(value => ({...value})),
});
}
function intersects(annotation, bounds) {
const left = annotation.type === 'arrow' ? Math.min(annotation.startX, annotation.endX) : annotation.x;
const top = annotation.type === 'arrow' ? Math.min(annotation.startY, annotation.endY) : annotation.y;
const right = annotation.type === 'arrow' ? Math.max(annotation.startX, annotation.endX) : annotation.x + annotation.width;
const bottom = annotation.type === 'arrow' ? Math.max(annotation.startY, annotation.endY) : annotation.y + annotation.height;
return left < bounds.x + bounds.width && top < bounds.y + bounds.height && right > bounds.x && bottom > bounds.y;
}
function clampAnnotation(annotation) {
if (annotation.type === 'highlight') {
const x = Math.max(crop.x, annotation.x);
const y = Math.max(crop.y, annotation.y);
const right = Math.min(crop.x + crop.width, annotation.x + annotation.width);
const bottom = Math.min(crop.y + crop.height, annotation.y + annotation.height);
return { type:'highlight', x, y, width:Math.max(1, right - x), height:Math.max(1, bottom - y) };
}
const start = boundedPoint({x:annotation.startX, y:annotation.startY}, crop);
const end = boundedPoint({x:annotation.endX, y:annotation.endY}, crop);
return { type:'arrow', startX:start.x, startY:start.y, endX:end.x, endY:end.y };
}
function setCrop(value) {
remember();
crop = boundedRect(value, crop);
redactions = redactions.filter(rectangle =>
rectangle.x < crop.x + crop.width && rectangle.y < crop.y + crop.height &&
rectangle.x + rectangle.width > crop.x && rectangle.y + rectangle.height > crop.y
).map(rectangle => boundedRect(rectangle, crop));
annotations = annotations.filter(annotation => intersects(annotation, crop)).map(clampAnnotation);
return snapshot();
}
function addRedaction(value) {
remember();
redactions.push(boundedRect(value, crop));
return snapshot();
}
function addHighlight(value) {
remember();
annotations.push({ type:'highlight', ...boundedRect(value, crop) });
return snapshot();
}
function addArrow(value) {
remember();
const start = boundedPoint({x:value.startX, y:value.startY}, crop);
const end = boundedPoint({x:value.endX, y:value.endY}, crop);
annotations.push({ type:'arrow', startX:start.x, startY:start.y, endX:end.x, endY:end.y });
return snapshot();
}
function undo() {
const previous = history.pop();
if (previous) {
crop = previous.crop;
redactions = previous.redactions;
annotations = previous.annotations;
}
return snapshot();
}
function reset() {
remember();
crop = { ...full };
redactions = [];
annotations = [];
return snapshot();
}
function snapshot() {
return {
crop:{...crop}, redactions:redactions.map(value => ({...value})),
annotations:annotations.map(value => ({...value})),
};
}
return { addArrow, addHighlight, addRedaction, reset, setCrop, snapshot, undo };
}
function namedBlob(blob, name) {
if (typeof File === 'function') return new File([blob], name, {type:blob.type});
Object.defineProperty(blob, 'name', {value:name, configurable:true});
return blob;
}
function paint(options) {
const state = options.model.snapshot();
const maxDimension = Number.isFinite(options.maxDimension) ? options.maxDimension : Infinity;
const scale = Math.min(1, maxDimension / Math.max(state.crop.width, state.crop.height));
const width = Math.max(1, Math.round(state.crop.width * scale));
const height = Math.max(1, Math.round(state.crop.height * scale));
options.canvas.width = width;
options.canvas.height = height;
const context = options.canvas.getContext('2d');
if (!context) throw new Error('Screenshot editing is unavailable in this browser.');
context.drawImage(options.source, state.crop.x, state.crop.y, state.crop.width, state.crop.height, 0, 0, width, height);
context.fillStyle = '#000000';
state.redactions.forEach(rectangle => context.fillRect(
Math.round((rectangle.x - state.crop.x) * scale),
Math.round((rectangle.y - state.crop.y) * scale),
Math.round(rectangle.width * scale),
Math.round(rectangle.height * scale),
));
state.annotations.forEach(annotation => {
if (annotation.type === 'highlight') {
context.fillStyle = 'rgba(250, 204, 21, 0.38)';
context.fillRect(
Math.round((annotation.x - state.crop.x) * scale),
Math.round((annotation.y - state.crop.y) * scale),
Math.round(annotation.width * scale),
Math.round(annotation.height * scale),
);
return;
}
const startX = (annotation.startX - state.crop.x) * scale;
const startY = (annotation.startY - state.crop.y) * scale;
const endX = (annotation.endX - state.crop.x) * scale;
const endY = (annotation.endY - state.crop.y) * scale;
const angle = Math.atan2(endY - startY, endX - startX);
const head = Math.max(10, Math.min(24, 16 * scale));
context.save();
context.strokeStyle = '#facc15';
context.lineWidth = Math.max(4, 6 * scale);
context.lineCap = 'round';
context.lineJoin = 'round';
context.beginPath();
context.moveTo(Math.round(startX), Math.round(startY));
context.lineTo(Math.round(endX), Math.round(endY));
context.lineTo(endX - head * Math.cos(angle - Math.PI / 6), endY - head * Math.sin(angle - Math.PI / 6));
context.moveTo(Math.round(endX), Math.round(endY));
context.lineTo(endX - head * Math.cos(angle + Math.PI / 6), endY - head * Math.sin(angle + Math.PI / 6));
context.stroke();
context.restore();
});
return state;
}
async function flatten(options) {
paint(options);
const type = ['image/png', 'image/jpeg', 'image/webp'].includes(options.type) ? options.type : 'image/png';
const blob = await new Promise(resolve => options.canvas.toBlob(resolve, type, type === 'image/png' ? undefined : 0.9));
if (!blob || !blob.size) throw new Error('The edited screenshot could not be saved. Try again.');
return namedBlob(blob, options.name || 'edited-screenshot.png');
}
function attachmentBlob(value) {
if (value.blob) return value.blob;
const binary = atob(String(value.data || ''));
return new Blob([Uint8Array.from(binary, character => character.charCodeAt(0))], {type:value.contentType});
}
function mount(options) {
let source = null;
let model = null;
let mode = 'redact';
let start = null;
let selectedIndex = -1;
let previousFocus = null;
function status(message) { options.status.textContent = message; }
function setMode(value) {
mode = value;
options.crop.setAttribute('aria-pressed', value === 'crop' ? 'true' : 'false');
options.redact.setAttribute('aria-pressed', value === 'redact' ? 'true' : 'false');
options.highlight.setAttribute('aria-pressed', value === 'highlight' ? 'true' : 'false');
options.arrow.setAttribute('aria-pressed', value === 'arrow' ? 'true' : 'false');
status({
crop:'Drag around the part to keep.', redact:'Drag over private information to hide it.',
highlight:'Drag around the detail to highlight.', arrow:'Drag toward the detail you want to point out.',
}[value]);
}
function render() {
if (source && model) paint({source, model, canvas:options.canvas, maxDimension:1600});
}
function close() {
options.dialog.hidden = true;
if (source && typeof source.close === 'function') source.close();
source = null;
model = null;
start = null;
(previousFocus || options.edit).focus();
}
async function open() {
const value = await options.controller.serialize();
const values = (Array.isArray(value) ? value : [value]).filter(Boolean);
selectedIndex = options.getActiveIndex();
const selected = values[selectedIndex];
if (!selected) return;
previousFocus = options.document.activeElement;
status('Opening screenshot editor…');
try {
const decode = options.decode || globalThis.createImageBitmap;
if (typeof decode !== 'function') throw new Error('decode');
source = await decode(attachmentBlob(selected));
model = createModel({width:source.width, height:source.height});
options.dialog.hidden = false;
render();
setMode('redact');
options.redact.focus();
} catch (_error) {
source = null;
status('This browser cannot edit the screenshot. Your original is unchanged.');
}
}
function point(event) {
const box = options.canvas.getBoundingClientRect();
const state = model.snapshot();
return {
x:state.crop.x + Math.round((event.clientX - box.left) * state.crop.width / box.width),
y:state.crop.y + Math.round((event.clientY - box.top) * state.crop.height / box.height),
};
}
options.canvas.addEventListener('pointerdown', event => {
if (!model) return;
start = point(event);
options.canvas.setPointerCapture?.(event.pointerId);
});
options.canvas.addEventListener('pointerup', event => {
if (!model || !start) return;
const end = point(event);
const dragStart = start;
const rectangle = {
x:Math.min(dragStart.x, end.x), y:Math.min(dragStart.y, end.y),
width:Math.abs(end.x - dragStart.x), height:Math.abs(end.y - dragStart.y),
};
start = null;
const tooSmall = mode === 'arrow' ? Math.hypot(end.x - dragStart.x, end.y - dragStart.y) < 8 :
rectangle.width < 3 || rectangle.height < 3;
if (tooSmall) {
status('Drag a larger area on the screenshot.');
return;
}
if (mode === 'crop') model.setCrop(rectangle);
else if (mode === 'redact') model.addRedaction(rectangle);
else if (mode === 'highlight') model.addHighlight(rectangle);
else model.addArrow({startX:dragStart.x, startY:dragStart.y, endX:end.x, endY:end.y});
render();
status({
crop:'Crop applied. Undo or reset if needed.', redact:'Private area hidden with an opaque redaction.',
highlight:'Highlight added.', arrow:'Arrow added.',
}[mode]);
});
options.edit.addEventListener('click', open);
options.crop.addEventListener('click', () => setMode('crop'));
options.redact.addEventListener('click', () => setMode('redact'));
options.highlight.addEventListener('click', () => setMode('highlight'));
options.arrow.addEventListener('click', () => setMode('arrow'));
options.undo.addEventListener('click', () => { if (model) { model.undo(); render(); status('Last edit undone.'); } });
options.reset.addEventListener('click', () => { if (model) { model.reset(); render(); status('Crop, redactions, and annotations reset.'); } });
options.cancel.addEventListener('click', close);
options.dialog.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); close(); } });
options.apply.addEventListener('click', async () => {
if (!model || !source) return;
options.apply.disabled = true;
status('Applying flattened edit…');
try {
const current = await options.controller.serialize();
const values = Array.isArray(current) ? current : [current];
const selected = values[selectedIndex];
let derivative = await flatten({
source, model, canvas:options.exportCanvas, maxDimension:2048,
name:selected.filename, type:selected.contentType,
});
if (options.optimizeImage) derivative = await options.optimizeImage(derivative);
options.controller.replace(selectedIndex, derivative);
await options.onApplied(selectedIndex);
close();
} catch (error) {
status(error.message || 'The edited screenshot could not be applied. Your original is unchanged.');
} finally {
options.apply.disabled = false;
}
});
return { close, open };
}
return { createModel, flatten, mount, paint };
});
+176
View File
@@ -0,0 +1,176 @@
(function(root, factory) {
const api = factory();
if (typeof module === 'object' && module.exports) module.exports = api;
else root.issueEvidenceReview = api;
})(typeof self !== 'undefined' ? self : this, function() {
'use strict';
const MAX_BYTES = 2 * 1024 * 1024;
function namedBlob(blob, name) {
if (typeof File === 'function') return new File([blob], name, { type: blob.type });
Object.defineProperty(blob, 'name', { value: name, configurable: true });
return blob;
}
async function optimizeImage(file, environment = {}) {
if (file.size <= MAX_BYTES) return file;
const decode = environment.createImageBitmap || globalThis.createImageBitmap;
const makeCanvas = environment.createCanvas || (() => document.createElement('canvas'));
if (typeof decode !== 'function') throw new Error('This browser cannot optimize the screenshot. Try cropping it and choose it again.');
let bitmap;
try {
bitmap = await decode(file);
const canvas = makeCanvas();
const context = canvas && canvas.getContext && canvas.getContext('2d');
if (!context || !bitmap.width || !bitmap.height) throw new Error('decode');
let scale = Math.min(1, Math.sqrt(MAX_BYTES / file.size) * 0.92);
for (let attempt = 0; attempt < 10; attempt += 1) {
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
const blob = await new Promise(resolve => canvas.toBlob(resolve, file.type, file.type === 'image/png' ? undefined : 0.86));
if (!blob) throw new Error('encode');
if (blob.size > 0 && blob.size <= MAX_BYTES) return namedBlob(blob, file.name);
scale *= 0.8;
}
} catch (_error) {
throw new Error('The screenshot could not be optimized. Try cropping it and choose it again.');
} finally {
if (bitmap && typeof bitmap.close === 'function') bitmap.close();
}
throw new Error('The screenshot could not be optimized below 2 MB. Try cropping it and choose it again.');
}
function create(options) {
const controller = options.controller;
const documentRef = options.document || document;
let activeIndex = 0;
let busy = false;
let previewUrl = '';
let thumbnailUrls = [];
function revoke(url) {
if (url && !url.startsWith('data:')) options.revokeObjectURL(url);
}
function attachmentUrl(attachment) {
return attachment?.blob ? options.createObjectURL(attachment.blob) :
'data:' + attachment.contentType + ';base64,' + attachment.data;
}
function count() {
const value = controller.state();
return Array.isArray(value) ? value.length : (value ? 1 : 0);
}
function setBusy(value) {
busy = Boolean(value);
options.earlier.disabled = busy || activeIndex <= 0;
options.later.disabled = busy || activeIndex >= count() - 1;
if (options.note) options.note.disabled = busy;
if (options.edit) options.edit.disabled = busy || !count();
Array.from(options.tray.children || []).forEach(button => { button.disabled = busy; });
}
function updateNote(values) {
if (!options.note) return;
options.note.value = controller.note(activeIndex);
options.note.disabled = busy;
if (options.noteLabel) {
options.noteLabel.textContent = 'Evidence note for screenshot ' + (activeIndex + 1) + ' of ' +
values.length + ' (optional)';
}
}
function update(values, optimized = false) {
if (!values.length) return;
activeIndex = Math.max(0, Math.min(activeIndex, values.length - 1));
revoke(previewUrl);
previewUrl = attachmentUrl(values[activeIndex]);
options.image.src = previewUrl;
const current = values[activeIndex];
const size = current.blob ? current.blob.size : Math.max(1, Math.floor(String(current.data || '').length * 3 / 4));
options.meta.textContent = 'Screenshot ' + (activeIndex + 1) + ' of ' + values.length + ' · ' +
current.filename + ' · ' + Math.ceil(size / 1024) + ' KB';
options.preview.hidden = false;
if (options.edit) options.edit.disabled = busy;
Array.from(options.tray.children || []).forEach((button, index) =>
button.setAttribute('aria-pressed', index === activeIndex ? 'true' : 'false'));
options.earlier.disabled = busy || activeIndex === 0;
options.later.disabled = busy || activeIndex === values.length - 1;
updateNote(values);
options.status.textContent = optimized ? 'Screenshots optimized and ready to file in this order.' :
values.length + ' screenshots ready to file in this order.';
}
function render(value, index = activeIndex, optimized = false) {
const values = (Array.isArray(value) ? value : [value]).filter(Boolean);
activeIndex = Math.max(0, Math.min(index, values.length - 1));
thumbnailUrls.forEach(revoke);
thumbnailUrls = [];
options.tray.replaceChildren(...values.map((item, itemIndex) => {
const button = documentRef.createElement('button');
button.type = 'button';
button.className = 'issue-evidence-thumbnail';
button.setAttribute('aria-label', 'Review screenshot ' + (itemIndex + 1) + ' of ' + values.length + ': ' + item.filename);
const thumbnail = documentRef.createElement('img');
thumbnail.alt = '';
thumbnail.src = attachmentUrl(item);
thumbnailUrls.push(thumbnail.src);
button.appendChild(thumbnail);
const position = documentRef.createElement('span');
position.textContent = String(itemIndex + 1);
button.appendChild(position);
button.addEventListener('click', () => { activeIndex = itemIndex; update(values); });
return button;
}));
options.tray.hidden = !values.length;
if (values.length) update(values, optimized);
}
function clear() {
revoke(previewUrl);
thumbnailUrls.forEach(revoke);
previewUrl = '';
thumbnailUrls = [];
activeIndex = 0;
options.tray.replaceChildren();
options.tray.hidden = true;
options.earlier.disabled = true;
options.later.disabled = true;
if (options.note) {
options.note.value = '';
options.note.disabled = true;
}
if (options.edit) options.edit.disabled = true;
if (options.noteLabel) options.noteLabel.textContent = 'Evidence note (optional)';
}
function afterRemoval(removedIndex, previousCount) {
activeIndex = Math.min(removedIndex, previousCount - 2);
}
function move(offset) {
const total = count();
const destination = activeIndex + offset;
if (destination < 0 || destination >= total) return Promise.resolve();
controller.move(activeIndex, destination);
activeIndex = destination;
return controller.serialize().then(value => {
render(value, activeIndex);
options.status.textContent = 'Screenshot moved to position ' + (activeIndex + 1) + ' of ' + total + '.';
});
}
options.earlier.addEventListener('click', () => move(-1));
options.later.addEventListener('click', () => move(1));
options.note?.addEventListener('input', event => {
controller.setNote(activeIndex, event.target.value);
});
clear();
return { activeIndex: () => activeIndex, afterRemoval, clear, render, setBusy };
}
return { create, optimizeImage };
});
+76 -20
View File
@@ -11,10 +11,22 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
const blob = value?.blob;
const data = String(value?.data || '');
if (!filename || !['image/png', 'image/jpeg', 'image/webp'].includes(contentType)) return undefined;
if (blob) return { filename, contentType, blob };
if (!data && value?.stored === true) return { filename, contentType, stored: true };
const note = String(value?.note || '').replace(/\s+/g, ' ').trim().slice(0, 240);
const noteValue = note ? { note } : {};
if (blob) return { filename, contentType, blob, ...noteValue };
if (!data && value?.stored === true) return { filename, contentType, stored: true, ...noteValue };
if (!data) return undefined;
return { filename, contentType, data };
return { filename, contentType, data, ...noteValue };
}
function captureAttachments(values) {
if (!Array.isArray(values)) return undefined;
if (values.length > 5) throw new Error('You can attach up to 5 screenshots.');
const attachments = values.map(captureAttachment);
if (attachments.some(value => !value)) {
throw new Error('Some screenshots are unavailable. Choose them again before queueing.');
}
return attachments.length ? attachments : undefined;
}
function read() {
@@ -56,6 +68,8 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
if (draft?.completionIntent === 'create-and-start') item.completionIntent = 'create-and-start';
const attachment = captureAttachment(draft?.attachment);
if (attachment) item.attachment = attachment;
const attachments = captureAttachments(draft?.attachments);
if (attachments) item.attachments = attachments;
item.operationId = item.id;
if (Number.isInteger(Number(draft?.milestoneId)) && Number(draft.milestoneId) > 0) {
item.milestoneId = Number(draft.milestoneId);
@@ -65,14 +79,21 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
}
function localIndexItem(item) {
if (!item?.attachment?.data && !item?.attachment?.blob) return item;
const hasAttachmentBytes = item?.attachment?.data || item?.attachment?.blob;
const hasBundleBytes = Array.isArray(item?.attachments) &&
item.attachments.some(value => value?.data || value?.blob);
if (!hasAttachmentBytes && !hasBundleBytes) return item;
return {
...item,
attachment: {
...(hasAttachmentBytes ? {attachment: {
filename: item.attachment.filename,
contentType: item.attachment.contentType,
stored: true,
},
}} : {}),
...(Array.isArray(item.attachments) ? {attachments:item.attachments.map(value => ({
filename:value.filename, contentType:value.contentType, stored:true,
...(value.note ? {note:value.note} : {}),
}))} : {}),
};
}
@@ -120,16 +141,25 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
async function hydrateForEdit(id) {
const item = read().find(candidate => candidate.id === id);
if (!item) return null;
if (!item.attachment?.stored || item.attachment.data || item.attachment.blob) return { ...item };
const storedBundle = Array.isArray(item.attachments) && item.attachments.some(value => value?.stored);
const storedAttachment = item.attachment?.stored && !item.attachment.data && !item.attachment.blob;
if (!storedAttachment && !storedBundle) return { ...item };
if (!backgroundSync?.get) {
throw new Error('The saved screenshot is unavailable. Retry before editing this issue.');
}
const durable = await backgroundSync.get(id);
const attachment = captureAttachment(durable?.attachment);
if ((!attachment?.data && !attachment?.blob) || durable?.operationId !== item.operationId) {
const attachments = captureAttachments(durable?.attachments);
if (durable?.operationId !== item.operationId ||
(storedAttachment && (!attachment?.data && !attachment?.blob)) ||
(storedBundle && (!attachments || attachments.length !== item.attachments.length))) {
throw new Error('The saved screenshot is unavailable. Retry before editing this issue.');
}
return { ...item, attachment };
return {
...item,
...(attachment ? {attachment} : {}),
...(attachments ? {attachments} : {}),
};
}
function prepareUpdate(id, draft) {
@@ -145,7 +175,9 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
const nextDueDate = /^\d{4}-\d{2}-\d{2}$/.test(String(draft?.dueDate || ''))
? String(draft.dueDate) : undefined;
const nextAttachment = captureAttachment(draft?.attachment);
const attachmentChanged = JSON.stringify(item.attachment || null) !== JSON.stringify(nextAttachment || null);
const nextAttachments = captureAttachments(draft?.attachments);
const attachmentChanged = JSON.stringify(item.attachment || null) !== JSON.stringify(nextAttachment || null) ||
JSON.stringify(item.attachments || null) !== JSON.stringify(nextAttachments || null);
const changed = item.repository !== nextRepository || item.title !== nextTitle || item.body !== nextBody
|| JSON.stringify(item.labelIds || []) !== JSON.stringify(nextLabelIds)
|| item.milestoneId !== nextMilestoneId || item.dueDate !== nextDueDate
@@ -154,7 +186,8 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
...item,
repository: nextRepository, title: nextTitle,
body: nextBody, labelIds: nextLabelIds,
milestoneId: nextMilestoneId, dueDate: nextDueDate, attachment: nextAttachment,
milestoneId: nextMilestoneId, dueDate: nextDueDate,
attachment: nextAttachment, attachments:nextAttachments,
operationId: changed ? String(operationId()).slice(0, 128) : item.operationId,
status: 'queued',
};
@@ -163,7 +196,11 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
if (nextMilestoneId === undefined) delete updated.milestoneId;
if (nextDueDate === undefined) delete updated.dueDate;
if (nextAttachment === undefined) delete updated.attachment;
if (attachmentChanged) delete updated.attachmentMarkdown;
if (nextAttachments === undefined) delete updated.attachments;
if (attachmentChanged) {
delete updated.attachmentMarkdown;
delete updated.attachmentMarkdowns;
}
delete updated.error;
delete updated.deliveryState;
return updated;
@@ -213,6 +250,13 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
return String(operationId || '').slice(0, 128 - suffix.length) + suffix;
}
function evidenceMarkdown(attachment, markdown, index) {
const note = String(attachment?.note || '').replace(/\s+/g, ' ').trim().slice(0, 240);
if (!note) return markdown;
const escaped = note.replace(/([\\`*_[\]{}()<>#+\-.!|])/g, '\\$1');
return '**Screenshot ' + (index + 1) + ' — ' + escaped + '**\n\n' + markdown;
}
function attachmentMultipart(attachment) {
let blob = attachment?.blob;
if (!blob && attachment?.data) {
@@ -241,30 +285,42 @@ function createIssueOutbox({ storage, fetchJson, coordinator, backgroundSync, ge
...(item.dueDate ? { due_date: item.dueDate + 'T23:59:59Z' } : {}),
}),
});
if (item.attachment) persistDeliveryStage(item.id, { deliveredIssue: issue });
if (item.attachment || item.attachments) persistDeliveryStage(item.id, { deliveredIssue: issue });
}
if (!item.attachment) return issue;
let markdown = item.attachmentMarkdown;
if (!markdown) {
const attachments = Array.isArray(item.attachments) ? item.attachments :
(item.attachment ? [item.attachment] : []);
if (!attachments.length) return issue;
const markdowns = Array.isArray(item.attachmentMarkdowns)
? item.attachmentMarkdowns.slice(0, attachments.length)
: (item.attachmentMarkdown ? [item.attachmentMarkdown] : []);
for (let index = markdowns.length; index < attachments.length; index += 1) {
const uploaded = await fetchJson(
'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(issue.number) + '/attachments',
{
method: 'POST',
headers: {
Accept: 'application/json',
'Idempotency-Key': stageOperationId(item.operationId, 'attachment'),
'Idempotency-Key': stageOperationId(
item.operationId, attachments.length === 1 ? 'attachment' : 'attachment-' + index,
),
},
body: attachmentMultipart(item.attachment),
body: attachmentMultipart(attachments[index]),
},
);
markdown = String(uploaded?.markdown || '');
const markdown = String(uploaded?.markdown || '');
if (!markdown) {
const error = new Error('The server did not confirm the screenshot upload.');
error.status = 422;
throw error;
}
persistDeliveryStage(item.id, { deliveredIssue: issue, attachmentMarkdown: markdown });
markdowns.push(markdown);
persistDeliveryStage(item.id, {
deliveredIssue: issue, attachmentMarkdowns:markdowns.slice(),
...(attachments.length === 1 ? {attachmentMarkdown:markdown} : {}),
});
}
const markdown = markdowns.map((value, index) =>
evidenceMarkdown(attachments[index], value, index)).join('\n\n');
await fetchJson(
'api/v1/repos/' + repository + '/issues/' + encodeURIComponent(issue.number) + '/comments',
{
+2 -1
View File
@@ -90,7 +90,8 @@ function createLaterPicker({
onState({ open:true, message:result.message, value:String(input || '') });
return false;
}
const confirmed = onConfirm(item, result.value, context);
const confirmed = typeof item?.confirm === 'function' ? item.confirm(result.value) :
onConfirm(item, result.value, context);
if (confirmed !== true && typeof confirmed !== 'function') return false;
committed = true;
afterClose = typeof confirmed === 'function' ? confirmed : null;
+159
View File
@@ -0,0 +1,159 @@
(function (root, factory) {
const createSavedSearches = factory();
if (typeof module === 'object' && module.exports) module.exports = createSavedSearches;
if (root) root.createSavedSearches = createSavedSearches;
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
function createSavedSearches(options) {
const fetchJson = options.fetchJson;
const createId = options.createId || (() => crypto.randomUUID().replace(/-/g, ''));
const onOpen = options.onOpen;
const onState = options.onState || (() => {});
let current = { revision:0, views:[] };
function snapshot() {
return { revision:current.revision, views:current.views.map(view => ({ ...view })) };
}
function publish(status, message) {
onState({ ...snapshot(), status, ...(message ? { message } : {}) });
}
function normalizeSearch(name, search, id) {
const cleanName = String(name || '').trim();
const query = String(search?.query || '').trim();
if (!cleanName || cleanName.length > 60) throw new Error('Name must be between 1 and 60 characters.');
if (query.length < 2 || query.length > 200) throw new Error('Search query must be between 2 and 200 characters.');
return {
id, name:cleanName, query,
kind:['all', 'issue', 'pull'].includes(search?.kind) ? search.kind : 'all',
state:['all', 'open', 'closed'].includes(search?.state) ? search.state : 'all',
repository:String(search?.repository || '').trim(),
};
}
async function replace(views) {
publish('saving');
try {
current = await fetchJson('api/v1/saved-searches', {
method:'PUT', headers:{ 'Content-Type':'application/json' },
body:JSON.stringify({ revision:current.revision, views }),
});
publish('ready');
return snapshot();
} catch (error) {
const conflict = error?.status === 409 && error?.payload?.detail?.snapshot;
if (conflict) {
current = conflict;
publish('conflict', 'Saved searches changed on another device.');
} else {
publish('error', 'Saved searches could not sync. Search still works.');
}
throw error;
}
}
return {
async load() {
publish('loading');
try {
current = await fetchJson('api/v1/saved-searches');
publish('ready');
} catch (error) {
publish('error', 'Saved searches could not load. Search still works.');
}
return snapshot();
},
save(name, search) {
if (current.views.length >= 20) return Promise.reject(new Error('Saved searches are limited to 20.'));
const created = normalizeSearch(name, search, createId());
return replace(current.views.concat(created));
},
rename(id, name) {
const existing = current.views.find(view => view.id === id);
if (!existing) return Promise.reject(new Error('Saved search no longer exists.'));
const changed = normalizeSearch(name, existing, existing.id);
return replace(current.views.map(view => view.id === id ? changed : view));
},
remove(id) {
if (!current.views.some(view => view.id === id)) return Promise.resolve(snapshot());
return replace(current.views.filter(view => view.id !== id));
},
open(id) {
const selected = current.views.find(view => view.id === id);
if (selected) onOpen({ ...selected });
},
snapshot,
};
}
createSavedSearches.mount = function mountSavedSearches(document, fetch, search, applyScope, history) {
const query = selector => document.querySelector(selector);
const input = query('#cmd-input');
const request = async (url, init) => {
const response = await fetch(url, init);
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
const error = new Error(payload.detail?.message || payload.detail || 'Saved Search request failed.');
error.status = response.status;
error.payload = payload;
throw error;
}
return payload;
};
let controller;
function render(state) {
const list = query('#saved-search-list');
const status = query('#saved-search-status');
list.replaceChildren();
status.textContent = ({loading:'Loading…', saving:'Syncing…', ready:'',
conflict:state.message, error:state.message})[state.status] || '';
state.views.forEach(view => {
const row = document.createElement('div');
row.className = 'saved-search-row';
const open = document.createElement('button');
open.type = 'button'; open.className = 'saved-search-open saved-search-action';
open.textContent = view.name; open.title = view.query;
open.addEventListener('click', () => controller.open(view.id));
const actions = document.createElement('div');
actions.className = 'saved-search-row-actions';
for (const action of ['Rename', 'Delete']) {
const button = document.createElement('button');
button.type = 'button'; button.className = 'saved-search-action'; button.textContent = action;
button.setAttribute('aria-label', action + ' ' + view.name);
button.addEventListener('click', async () => {
if (action === 'Rename') {
const name = globalThis.prompt('Rename saved search', view.name);
if (name !== null && name.trim()) await controller.rename(view.id, name).catch(() => {});
} else if (globalThis.confirm('Delete saved search “' + view.name + '”?')) {
await controller.remove(view.id).catch(() => {});
}
});
actions.append(button);
}
row.append(open, actions); list.append(row);
});
}
controller = createSavedSearches({ fetchJson:request, onState:render, onOpen:view => {
search.setQuery('');
input.value = view.query;
applyScope(view);
search.setQuery(view.query);
history.update({query:view.query, scope:view});
input.focus();
}});
query('#save-current-search').addEventListener('click', async () => {
const name = query('#saved-search-name').value.trim();
const current = {query:input.value.trim(), kind:query('#cmd-search-kind').value,
state:query('#cmd-search-state').value, repository:query('#cmd-search-repository').value.trim()};
if (!name || current.query.length < 2) {
query('#saved-search-status').textContent = 'Enter a name and at least 2 search characters.';
return;
}
await controller.save(name, current).then(() => { query('#saved-search-name').value = ''; })
.catch(error => { query('#saved-search-status').textContent = error.message; });
});
return controller;
};
return createSavedSearches;
});
+197 -6
View File
@@ -57,15 +57,23 @@
if (detail?.claimable) return claim(detail);
throw new Error('This issue is no longer available to assign.');
}
return { identity, eligible, start, cancel, toggle, snapshot, prepare, limit:maximum };
function releaseRepository() {
const repositories = new Set(Array.from(selected.values()).map(item => item.repository));
return repositories.size === 1 ? repositories.values().next().value : null;
}
return { identity, eligible, start, cancel, toggle, snapshot, prepare, releaseRepository, limit:maximum };
}
createSearchBatchPlan.mount = function mountSearchBatchPlanning(
document, batchFactory, todayWork, getOwner, fetchJson, previewPath, queueToday,
acceptIssue, lookup, render, escapeHtml, escapeAttribute
todaySync, acceptIssue, lookup, render, escapeHtml, escapeAttribute,
laterWork = null, laterPicker = null
) {
const get = selector => document.querySelector(selector);
let processor;
let laterProcessor;
let releaseProcessor;
let releaseContext = null;
const plan = createSearchBatchPlan({
resolve:item => fetchJson(previewPath(item), {headers:{Accept:'application/json'}}),
claim:detail => fetchJson(
@@ -77,6 +85,8 @@
get('#search-batch-actions').hidden = !state.active;
get('#select-search-results').hidden = state.active;
get('#queue-selected-search-results').disabled = state.count === 0;
get('#defer-selected-search-results').disabled = state.count === 0;
get('#plan-selected-search-results').disabled = state.count === 0;
get('#search-selection-status').textContent = state.count ?
state.count + ' issue' + (state.count === 1 ? '' : 's') + ' selected.' : 'No issues selected.';
render();
@@ -85,10 +95,24 @@
processor = batchFactory({
capacity:() => Math.max(0, todayWork.limit - todayWork.read().length),
owner:getOwner,
timeBudget:() => {
const planning = todayWork.planning();
return {
capacity_minutes:planning.capacity_minutes,
planned_minutes:Object.values(planning.estimates || {}).reduce((sum, minutes) => sum + minutes, 0),
};
},
journalName:'search-today-batch',
autoMount:false,
claim:item => plan.prepare(item),
queue:confirmed => queueToday(acceptIssue(confirmed)),
persistEstimate:(confirmed, minutes) => {
const planning = todayWork.planning();
planning.estimates[todayWork.identity(confirmed)] = minutes;
todayWork.replacePlanning(planning);
todaySync.enqueueConfiguration(planning.capacity_minutes, planning.estimates);
todaySync.flush();
},
onProgress:progress => {
get('#queue-selected-search-results').disabled = progress.status === 'running';
if (progress.status === 'running') {
@@ -96,19 +120,186 @@
} else if (progress.status === 'full') {
get('#search-selection-status').textContent = 'Today has ' + progress.available + ' remaining slot' +
(progress.available === 1 ? '.' : 's.');
} else if (progress.status === 'estimates-required') {
get('#search-batch-estimate-summary').textContent = 'Estimate every selected issue.';
} else if (progress.status === 'over-budget') {
get('#search-batch-estimate-summary').textContent = progress.requested_minutes +
' min selected · ' + progress.remaining_minutes + ' min remain.';
} else if (progress.status === 'complete') {
get('#cmd-search-action-status').textContent = progress.failed.length ?
progress.queued.length + ' queued · ' + progress.failed.length + ' need retry.' :
progress.queued.length + ' added to Today.';
get('#resume-search-batch').hidden = processor.pending() === 0;
closeEstimateReview();
if (!progress.failed.length) plan.cancel();
}
},
});
laterProcessor = batchFactory({
capacity:() => plan.limit,
owner:getOwner,
journalName:'search-later-batch',
queueFailureReason:'assigned but Later could not be saved',
autoMount:false,
claim:item => plan.prepare(item),
queue:(confirmed, context) => {
const outcome = laterWork?.defer(acceptIssue(confirmed), context?.until);
return outcome === 'deferred' ? 'queued' : outcome;
},
onProgress:progress => {
get('#defer-selected-search-results').disabled = progress.status === 'running';
if (progress.status === 'running') {
get('#search-selection-status').textContent = 'Deferring ' + progress.processed + ' of ' + progress.selected + '…';
} else if (progress.status === 'complete') {
get('#cmd-search-action-status').textContent = progress.failed.length ?
progress.queued.length + ' deferred · ' + progress.failed.length + ' need retry.' :
progress.queued.length + ' added to Later.';
restore();
if (!progress.failed.length) plan.cancel();
}
},
});
releaseProcessor = batchFactory({
capacity:() => plan.limit,
owner:getOwner,
journalName:'search-release-batch',
queueFailureReason:'assigned but release planning could not be confirmed',
autoMount:false,
claim:item => plan.prepare(item),
queue:async (confirmed, context) => {
const issuePath = 'api/v1/repos/' + confirmed.repository.split('/').map(encodeURIComponent).join('/') +
'/issues/' + encodeURIComponent(confirmed.number);
const releasePlan = await fetchJson(issuePath + '/release-plan', {
method:'PATCH', headers:{Accept:'application/json','Content-Type':'application/json'},
body:JSON.stringify({milestone_id:context.milestone_id, due_date:context.due_date || null}),
});
if (releasePlan?.number !== confirmed.number ||
releasePlan?.milestone?.id !== context.milestone_id ||
(context.due_date && releasePlan?.due_date !== context.due_date)) {
throw new Error('Issue release plan was not confirmed.');
}
return 'queued';
},
onProgress:progress => {
get('#confirm-search-release').disabled = progress.status === 'running';
if (progress.status === 'running') {
get('#search-release-summary').textContent = 'Planning ' + progress.processed + ' of ' + progress.selected + '…';
} else if (progress.status === 'complete') {
get('#cmd-search-action-status').textContent = progress.failed.length ?
progress.queued.length + ' planned · ' + progress.failed.length + ' need retry.' :
progress.queued.length + ' planned for ' + (releaseContext?.milestone_title || 'release') + '.';
get('#resume-search-batch').hidden = releaseProcessor.pending() === 0;
closeReleaseReview();
if (!progress.failed.length) plan.cancel();
}
},
});
function estimateValues() {
return Object.fromEntries(Array.from(document.querySelectorAll('[data-search-batch-estimate]')).map(input =>
[input.dataset.searchBatchEstimate, Number(input.value)]
));
}
function closeEstimateReview() {
get('#search-batch-estimate-review').hidden = true;
get('#search-batch-actions').hidden = !plan.snapshot().active;
}
function openEstimateReview(items) {
const planning = todayWork.planning();
const planned = Object.values(planning.estimates || {}).reduce((sum, minutes) => sum + minutes, 0);
const remaining = Math.max(0, planning.capacity_minutes - planned);
get('#search-batch-estimate-summary').textContent = remaining +
' min remain. Estimate before assigning.';
get('#search-batch-estimate-list').innerHTML = items.map(item => {
const id = String(item.repository || '') + '#' + String(item.number || '');
const estimate = planning.estimates?.[id] || '';
return '<div class="search-batch-estimate-row"><div><span class="small">' + escapeHtml(id) +
'</span><strong>' + escapeHtml(item.title || 'Untitled work') + '</strong></div><label class="small">' +
'<input type="number" inputmode="numeric" min="5" max="1440" step="5" value="' +
escapeAttribute(estimate) + '" data-search-batch-estimate="' + escapeAttribute(id) +
'" aria-label="Estimate for ' + escapeAttribute(item.title || id) + ' in minutes" /> min</label></div>';
}).join('');
get('#search-batch-actions').hidden = true;
get('#search-batch-estimate-review').hidden = false;
document.querySelector('[data-search-batch-estimate]')?.focus();
}
function closeReleaseReview() {
get('#search-release-review').hidden = true;
get('#search-batch-actions').hidden = !plan.snapshot().active;
}
async function openReleaseReview() {
const items = plan.snapshot().items;
const repository = plan.releaseRepository();
if (!items.length) return;
if (!repository) {
get('#search-selection-status').textContent = 'Select issues from one repository to plan a release.';
return;
}
get('#plan-selected-search-results').disabled = true;
get('#search-selection-status').textContent = 'Loading release milestones…';
try {
const milestones = await fetchJson(
'api/v1/repos/' + repository.split('/').map(encodeURIComponent).join('/') + '/milestones',
{headers:{Accept:'application/json'}}
);
const open = (Array.isArray(milestones) ? milestones : []).filter(item => item?.state !== 'closed');
get('#search-release-milestone').innerHTML = '<option value="">Choose milestone</option>' + open.map(item =>
'<option value="' + Number(item.id) + '">' + escapeHtml(item.title) + '</option>'
).join('');
get('#search-release-list').innerHTML = items.map(item => '<div class="search-release-row"><span>' +
escapeHtml(item.repository + ' #' + item.number) + '</span><strong>' +
escapeHtml(item.title || 'Untitled work') + '</strong></div>').join('');
get('#search-release-summary').textContent = items.length + ' issues in ' + repository + '. Assignment starts only after confirmation.';
get('#search-batch-actions').hidden = true;
get('#search-release-review').hidden = false;
get('#search-release-milestone').focus();
} catch (error) {
get('#search-selection-status').textContent = error?.message || 'Milestones could not be loaded. Try again.';
} finally {
get('#plan-selected-search-results').disabled = false;
}
}
get('#select-search-results').addEventListener('click', () => plan.start());
get('#cancel-search-selection').addEventListener('click', () => plan.cancel());
get('#queue-selected-search-results').addEventListener('click', () => processor.run(plan.snapshot().items));
get('#resume-search-batch').addEventListener('click', () => processor.resume());
get('#queue-selected-search-results').addEventListener('click', () => {
const items = plan.snapshot().items;
const capacity = todayWork.planning().capacity_minutes;
if (Number.isInteger(capacity) && capacity > 0) openEstimateReview(items);
else processor.run(items);
});
get('#defer-selected-search-results').addEventListener('click', event => {
const items = plan.snapshot().items;
if (!items.length) return;
laterPicker?.open({ items, confirm:until => () => laterProcessor.run(
items, {}, { until:new Date(until).toISOString() }
) }, event.currentTarget, 'search-batch');
});
get('#plan-selected-search-results').addEventListener('click', openReleaseReview);
get('#cancel-search-release').addEventListener('click', closeReleaseReview);
get('#confirm-search-release').addEventListener('click', () => {
const milestoneSelect = get('#search-release-milestone');
const milestoneId = Number(milestoneSelect.value);
if (!Number.isInteger(milestoneId) || milestoneId < 1) {
get('#search-release-summary').textContent = 'Choose an open milestone.';
return;
}
const selectedOption = milestoneSelect.options?.[milestoneSelect.selectedIndex];
const milestoneTitle = selectedOption?.textContent || selectedOption?.text || 'release';
const dueDay = get('#search-release-due-date').value;
releaseContext = {
milestone_id:milestoneId, milestone_title:milestoneTitle,
due_date:dueDay ? dueDay + 'T23:59:59Z' : null,
};
releaseProcessor.run(plan.snapshot().items, {}, releaseContext);
});
get('#cancel-search-batch-estimates').addEventListener('click', closeEstimateReview);
get('#confirm-search-batch-estimates').addEventListener('click', () =>
processor.run(plan.snapshot().items, estimateValues())
);
get('#resume-search-batch').addEventListener('click', () => {
if (processor.pending()) return processor.resume();
if (laterProcessor.pending()) return laterProcessor.resume();
return releaseProcessor.resume();
});
get('#open-palette').addEventListener('click', () => restore());
get('#cmd-results').addEventListener('change', event => {
const index = event.target?.dataset?.searchSelect;
@@ -117,7 +308,7 @@
if (result) plan.toggle(result);
});
function restore() {
const pending = processor.pending();
const pending = processor.pending() + laterProcessor.pending() + releaseProcessor.pending();
get('#resume-search-batch').hidden = pending === 0;
get('#resume-search-batch').textContent = 'Resume ' + pending + ' interrupted';
}
@@ -131,7 +322,7 @@
escapeHtml(result.repository) + ' #' + escapeHtml(result.number) + ' · ' +
(allowed ? 'Open issue' : 'Not eligible') + '</span></label>';
}
return { plan, processor, restore, resultHtml };
return { plan, processor, laterProcessor, releaseProcessor, restore, resultHtml };
};
return createSearchBatchPlan;
+19 -5
View File
@@ -17,6 +17,7 @@ const SHELL = [
BASE + 'static/security-center.js',
BASE + 'static/markdown.js',
BASE + 'static/commands.js',
BASE + 'static/saved-searches.js',
BASE + 'static/search-preview.js',
BASE + 'static/search-defer.js',
BASE + 'static/widgets.js',
@@ -63,6 +64,8 @@ const SHELL = [
BASE + 'static/search-batch-plan.js',
BASE + 'static/conversation.js',
BASE + 'static/comment-actions.js',
BASE + 'static/issue-evidence-review.js',
BASE + 'static/issue-evidence-editor.js',
BASE + 'static/issue-attachment.js',
BASE + 'static/issue-sheet.js',
BASE + 'static/create-issue-sheet.js',
@@ -114,17 +117,28 @@ async function acceptSharedContent(request) {
const images = form.getAll('image').filter(value => typeof value !== 'string' && value?.size > 0);
let marker = '';
await sharedAttachmentStore.delete(SHARED_IMAGE_ID).catch(() => {});
if (images.length > 1) marker = 'multiple';
else if (images.length === 1) {
const image = images[0];
if (!SHARED_IMAGE_TYPES.has(String(image.type || '')) || image.size > MAX_SHARED_IMAGE_BYTES) {
if (images.length > 5) marker = 'multiple';
else if (images.length > 0) {
const supported = images.every(image =>
SHARED_IMAGE_TYPES.has(String(image.type || '')) && image.size <= MAX_SHARED_IMAGE_BYTES
);
if (!supported) {
marker = 'unsupported';
} else {
} else if (images.length === 1) {
const image = images[0];
await sharedAttachmentStore.put(SHARED_IMAGE_ID, {
filename:String(image.name || 'shared-screenshot').slice(0, 255),
contentType:String(image.type), blob:image,
});
marker = 'image';
} else {
await sharedAttachmentStore.put(SHARED_IMAGE_ID, {
attachments:images.map(image => ({
filename:String(image.name || 'shared-screenshot').slice(0, 255),
contentType:String(image.type), blob:image,
})),
});
marker = 'images';
}
}
const target = new URL(BASE, self.location.origin);
+13 -1
View File
@@ -10,11 +10,23 @@
async function consume({marker, store, restore, status = () => {}}) {
if (!marker) return false;
if (marker !== 'image') {
if (!['image', 'images'].includes(marker)) {
status('Share one PNG, JPEG, or WebP screenshot.');
return false;
}
const value = await store?.get(RECORD_ID);
const attachments = Array.isArray(value?.attachments) ? value.attachments : null;
if (marker === 'images') {
if (!attachments?.length || attachments.length > 5 || attachments.some(attachment =>
!attachment?.blob || !attachment.filename || !TYPES.has(String(attachment.contentType || '')))) {
status('The shared screenshots are unavailable. Share them again.');
return false;
}
restore(attachments);
await store.delete(RECORD_ID);
status(attachments.length + ' shared screenshots ready to file with this issue.');
return true;
}
if (!value?.blob || !value.filename || !TYPES.has(String(value.contentType || ''))) {
status('The shared screenshot is unavailable. Share it again.');
return false;
+33 -4
View File
@@ -42,19 +42,35 @@ function createUnfiledCaptures({
const ownerLogin = String(getCaptureLogin() || '').trim();
if (!ownerLogin) throw new Error('Offline identity is unavailable. Reconnect once before saving private work.');
const attachment = note?.attachment;
const attachments = note?.attachments;
if (Array.isArray(attachments) && attachments.length > 5) {
throw new Error('You can attach up to 5 screenshots.');
}
const validAttachments = Array.isArray(attachments) && attachments.length > 0 &&
attachments.every(value => value?.blob && value?.filename &&
['image/png', 'image/jpeg', 'image/webp'].includes(String(value?.contentType || '')));
if (attachments && !validAttachments) {
throw new Error('One or more screenshots are unavailable. Choose them again before saving.');
}
const hasAttachment = Boolean(attachment?.blob && attachment?.filename &&
['image/png', 'image/jpeg', 'image/webp'].includes(String(attachment?.contentType || '')));
if (attachment && !hasAttachment) throw new Error('The screenshot is unavailable. Choose it again before saving.');
if (hasAttachment && !attachmentStore) {
if ((hasAttachment || validAttachments) && !attachmentStore) {
throw new Error('Screenshot storage is unavailable. Your capture is still open; retry after reloading.');
}
return {title, body, ownerLogin, attachment, hasAttachment};
return {
title, body, ownerLogin, attachment, attachments,
hasAttachment:hasAttachment || validAttachments,
attachmentCount:validAttachments ? attachments.length : (hasAttachment ? 1 : 0),
};
}
function persist(prepared, existing, removed = null) {
const item = {
id:String(createId()), ownerLogin:prepared.ownerLogin, title:prepared.title, body:prepared.body,
savedAt:Number(now()), ...(prepared.hasAttachment ? {hasAttachment:true} : {}),
savedAt:Number(now()), ...(prepared.hasAttachment ? {
hasAttachment:true, attachmentCount:prepared.attachmentCount,
} : {}),
};
const items = [item, ...existing.filter(candidate => candidate.id !== item.id)];
const writeItems = () => {
@@ -66,7 +82,13 @@ function createUnfiledCaptures({
return item;
};
const stage = prepared.hasAttachment
? Promise.resolve(attachmentStore.put(item.id, {
? Promise.resolve(attachmentStore.put(item.id, prepared.attachments ? {
attachments:prepared.attachments.map(value => ({
filename:String(value.filename).slice(0, 255),
contentType:String(value.contentType), blob:value.blob,
...(String(value.note || '').trim() ? {note:String(value.note).trim().slice(0, 240)} : {}),
})),
} : {
filename:String(prepared.attachment.filename).slice(0, 255),
contentType:String(prepared.attachment.contentType), blob:prepared.attachment.blob,
}))
@@ -137,6 +159,13 @@ function createUnfiledCaptures({
if (!item.hasAttachment) return draft;
if (!attachmentStore) throw new Error('The saved screenshot is unavailable. Retry after reloading.');
return Promise.resolve(attachmentStore.get(id)).then(attachment => {
if (Array.isArray(attachment?.attachments) && attachment.attachments.length) {
if (attachment.attachments.length > 5 || attachment.attachments.some(value =>
!value?.blob || !value?.filename || !value?.contentType)) {
throw new Error('The saved screenshots are unavailable. Keep this Draft and retry.');
}
return {...draft, attachments:attachment.attachments};
}
if (!attachment?.blob || !attachment?.filename || !attachment?.contentType) {
throw new Error('The saved screenshot is unavailable. Keep this Draft and retry.');
}
+6 -3
View File
@@ -22,18 +22,21 @@ COMMONJS_BROWSER_BRANCH = re.compile(
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"),
"issue-capture": (
"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",),
"device-setup": ("static/install-app.js", "static/mobile-device-setup.js"),
"security-center": ("static/security-center.js",),
"today-timer": (
"static/commands.js", "static/task-overlay-history.js", "static/search-preview.js", "static/search-defer.js", "static/mobile-search-viewport.js", "static/my-work.js", "static/protect-today.js", "static/mobile-task-dock.js", "static/mobile-queue-launcher.js", "static/update-triage-session.js", "static/update-review-handoff.js", "static/update-triage-launcher.js", "static/update-triage-gesture.js", "static/notification-undo.js", "static/today-timer.js", "static/today-recap.js",
"static/commands.js", "static/saved-searches.js", "static/task-overlay-history.js", "static/search-preview.js", "static/search-defer.js", "static/mobile-search-viewport.js", "static/my-work.js", "static/protect-today.js", "static/mobile-task-dock.js", "static/mobile-queue-launcher.js", "static/update-triage-session.js", "static/update-review-handoff.js", "static/update-triage-launcher.js", "static/update-triage-gesture.js", "static/notification-undo.js", "static/today-timer.js", "static/today-recap.js",
"static/today-rollover.js", "static/later-work.js", "static/drafts.js", "static/unfiled-captures.js",
"static/assign-and-start.js", "static/queue-today.js",
"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/search-batch-plan.js", "static/issue-evidence-review.js", "static/issue-evidence-editor.js",
"static/issue-attachment.js",
),
}
CACHE_DECLARATION = re.compile(
+52
View File
@@ -1969,6 +1969,58 @@ async def update_assigned_issue_milestone(
}
async def update_assigned_issue_release_plan(
repository: str, number: int, milestone_id: int, due_date: str | None
) -> dict:
path = f"repos/{repository}/issues/{number}"
login, issue = await _current_login_and_target(path)
if (
issue.get("state") != "open"
or isinstance(issue.get("pull_request"), dict)
or not _login_in_users(login, issue.get("assignees"))
):
raise IssueNotAvailableError("assigned issue not found")
selected = next(
(item for item in await repo_milestones(repository) if item["id"] == milestone_id),
None,
)
if selected is None:
raise ValueError("Unknown open repository milestone")
payload: dict = {"milestone": milestone_id}
if due_date is not None:
payload["due_date"] = due_date
response = await _get_client().patch(
f"/api/v1/{path}", headers=_auth(), json=payload
)
response.raise_for_status()
confirmed = response.json()
milestone_value = confirmed.get("milestone") if isinstance(confirmed, dict) else None
normalized = (
{"id": milestone_value["id"], "title": milestone_value["title"]}
if isinstance(milestone_value, dict)
and isinstance(milestone_value.get("id"), int)
and isinstance(milestone_value.get("title"), str)
else None
)
expected_due_date = due_date if due_date is not None else issue.get("due_date")
if (
not isinstance(confirmed, dict)
or confirmed.get("number") != number
or normalized != selected
or confirmed.get("due_date") != expected_due_date
):
raise ValueError("Gitea did not confirm the issue release plan")
return {
"repository": repository,
"number": number,
"state": confirmed.get("state", "open"),
"milestone": normalized,
"due_date": confirmed.get("due_date"),
}
async def issue_conversation_page(
repository: str,
number: int,
+108 -1
View File
@@ -57,6 +57,7 @@ from src.push_notifications import (
from src.push_endpoint_policy import UnsafePushEndpoint, validate_public_push_endpoint
from src.push_subscription_store import PushSubscriptionStore
from src.request_boundary import RequestBodyLimitMiddleware, request_body_limit
from src.saved_search_store import SavedSearchConflict, SavedSearchStore
from src.security_event_store import SecurityEventStore, SecurityEventStoreError
from src.suggestion_engine import compute
from src.later_store import LaterStore
@@ -617,6 +618,20 @@ class LaterOperationBatch(BaseModel):
operations: list[LaterOperation] = Field(min_length=1, max_length=50)
class SavedSearchView(BaseModel):
id: str = Field(min_length=1, max_length=64, pattern=r"^[A-Za-z0-9_-]+$")
name: str = Field(min_length=1, max_length=60)
query: str = Field(min_length=2, max_length=200)
kind: Literal["all", "issue", "pull"] = "all"
state: Literal["all", "open", "closed"] = "all"
repository: str = Field(default="", max_length=200)
class SavedSearchCollection(BaseModel):
revision: int = Field(ge=0)
views: list[SavedSearchView] = Field(max_length=20)
class NotificationLaterRequest(BaseModel):
wake_at: str = Field(min_length=1, max_length=100)
@@ -763,6 +778,15 @@ class IssueMilestoneUpdate(BaseModel):
milestone_id: PositiveInt | None = None
class IssueReleasePlanUpdate(BaseModel):
milestone_id: PositiveInt
due_date: str | None = Field(
default=None,
pattern=r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$",
max_length=20,
)
class IssueHandoff(BaseModel):
recipient: str = Field(
min_length=1, max_length=255, pattern=r"^[A-Za-z0-9_.-]+$"
@@ -1174,7 +1198,7 @@ async def require_operator_session(request: Request, call_next):
async def prevent_live_api_caching(request, call_next):
response = await call_next(request)
path = dashboard_auth.application_path(request)
if path in {"/api/v1/context", "/api/v1/background-identity", "/api/v1/events", "/api/v1/live", "/api/v1/available-issues", "/api/v1/search", "/api/v1/work-route", "/api/v1/today", "/api/v1/later", "/api/v1/security-events", "/api/v1/push-subscription"} or path.startswith("/api/v1/work/") or (
if path in {"/api/v1/context", "/api/v1/background-identity", "/api/v1/events", "/api/v1/live", "/api/v1/available-issues", "/api/v1/search", "/api/v1/work-route", "/api/v1/today", "/api/v1/later", "/api/v1/saved-searches", "/api/v1/security-events", "/api/v1/push-subscription"} or path.startswith("/api/v1/work/") or (
path.startswith("/api/v1/repos/")
and path.endswith("/review")
) or path.startswith("/api/v1/notifications") or (
@@ -2105,6 +2129,12 @@ def _later_store() -> LaterStore:
)
def _saved_search_store() -> SavedSearchStore:
return SavedSearchStore(
os.getenv("STACKCHAIN_SAVED_SEARCH_DB", str(_state_dir / "saved-searches.sqlite3"))
)
async def _confirmed_login() -> str:
try:
user = await asyncio.wait_for(
@@ -2120,6 +2150,49 @@ async def _confirmed_login() -> str:
return login.strip().lower()
@app.get("/api/v1/saved-searches")
async def get_saved_searches(response: Response):
login = await _confirmed_login()
try:
snapshot = await asyncio.to_thread(_saved_search_store().get, login)
except (OSError, sqlite3.Error):
raise HTTPException(
status_code=503,
detail="Saved Search synchronization is unavailable",
headers={"Retry-After": "1"},
)
response.headers["Cache-Control"] = "no-store"
return snapshot
@app.put("/api/v1/saved-searches")
async def replace_saved_searches(payload: SavedSearchCollection):
login = await _confirmed_login()
try:
return await asyncio.to_thread(
_saved_search_store().replace,
login,
payload.revision,
[view.model_dump() for view in payload.views],
)
except SavedSearchConflict as exc:
raise HTTPException(
status_code=409,
detail={
"message": "Saved searches changed on another device.",
"snapshot": exc.snapshot,
},
)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc))
except (OSError, sqlite3.Error):
raise HTTPException(
status_code=503,
detail="Saved Search synchronization is unavailable",
headers={"Retry-After": "1"},
)
@app.get("/api/v1/today")
async def get_today_plan():
login = await _confirmed_login()
@@ -4374,6 +4447,40 @@ async def update_assigned_issue_milestone(
return JSONResponse(result)
@app.patch("/api/v1/repos/{owner}/{repo}/issues/{number}/release-plan")
async def update_assigned_issue_release_plan(
update: IssueReleasePlanUpdate,
owner: str,
repo: str,
number: int = PathParam(gt=0),
):
repository = f"{owner}/{repo}"
try:
result = await asyncio.wait_for(
gitea_proxy.update_assigned_issue_release_plan(
repository, number, update.milestone_id, update.due_date
),
timeout=ISSUE_ACTION_TIMEOUT_SECONDS,
)
except gitea_proxy.IssueNotAvailableError:
raise HTTPException(status_code=404, detail="Assigned issue not found")
except ValueError as exc:
if str(exc) == "Unknown open repository milestone":
raise HTTPException(status_code=422, detail=str(exc))
return JSONResponse(
{"error": "The release plan could not be confirmed. Your selection is safe; please retry."},
status_code=503,
headers={"Retry-After": "1"},
)
except Exception:
return JSONResponse(
{"error": "The release plan could not be updated. Your selection is safe; please retry."},
status_code=503,
headers={"Retry-After": "1"},
)
return JSONResponse(result)
@app.get("/api/v1/repos/{owner}/{repo}/milestones")
async def repository_milestones(owner: str, repo: str):
repository = f"{owner}/{repo}"
+130
View File
@@ -0,0 +1,130 @@
"""Durable, account-scoped saved Search views."""
import json
import re
import sqlite3
from pathlib import Path
_REPOSITORY = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
_VIEW_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
class SavedSearchConflict(ValueError):
"""Raised when a client attempts to replace a stale collection."""
def __init__(self, snapshot: dict):
super().__init__("saved searches changed on another device")
self.snapshot = snapshot
class SavedSearchStore:
def __init__(self, path: str | Path, *, limit: int = 20, timeout: float = 1.0):
self.path = Path(path)
self.limit = limit
self.timeout = timeout
self._initialize()
def _initialize(self) -> None:
self.path.parent.mkdir(parents=True, exist_ok=True)
with sqlite3.connect(self.path, timeout=self.timeout) as connection:
connection.execute("PRAGMA journal_mode=WAL")
connection.execute(
"""
CREATE TABLE IF NOT EXISTS saved_searches (
login TEXT PRIMARY KEY,
revision INTEGER NOT NULL,
views TEXT NOT NULL
)
"""
)
def _connect(self) -> sqlite3.Connection:
return sqlite3.connect(self.path, timeout=self.timeout)
@staticmethod
def _login(login: str) -> str:
normalized = login.strip().lower()
if not normalized:
raise ValueError("login is required")
return normalized
@staticmethod
def _snapshot(row) -> dict:
return {"revision": 0, "views": []} if row is None else {
"revision": int(row[0]), "views": json.loads(row[1])
}
def get(self, login: str) -> dict:
with self._connect() as connection:
row = connection.execute(
"SELECT revision, views FROM saved_searches WHERE login = ?",
(self._login(login),),
).fetchone()
return self._snapshot(row)
def _normalize(self, views: list[dict]) -> list[dict]:
if not isinstance(views, list):
raise ValueError("views must be a list")
if len(views) > self.limit:
raise ValueError(f"saved searches are limited to {self.limit}")
normalized = []
seen = set()
for raw in views:
if not isinstance(raw, dict):
raise ValueError("saved search must be an object")
view_id = raw.get("id")
if not isinstance(view_id, str) or not _VIEW_ID.fullmatch(view_id):
raise ValueError("id is invalid")
if view_id in seen:
raise ValueError("saved search ids must be unique")
name = raw.get("name")
if not isinstance(name, str) or not name.strip():
raise ValueError("name is required")
name = name.strip()
if len(name) > 60:
raise ValueError("name must be at most 60 characters")
query = raw.get("query")
if not isinstance(query, str) or not 2 <= len(query.strip()) <= 200:
raise ValueError("query must be between 2 and 200 characters")
kind = raw.get("kind", "all")
state = raw.get("state", "all")
if kind not in {"all", "issue", "pull"}:
raise ValueError("kind is invalid")
if state not in {"all", "open", "closed"}:
raise ValueError("state is invalid")
repository = raw.get("repository", "")
if not isinstance(repository, str) or (repository and not _REPOSITORY.fullmatch(repository)):
raise ValueError("repository is invalid")
seen.add(view_id)
normalized.append({
"id": view_id,
"name": name,
"query": query.strip(),
"kind": kind,
"state": state,
"repository": repository,
})
return normalized
def replace(self, login: str, expected_revision: int, views: list[dict]) -> dict:
login = self._login(login)
if not isinstance(expected_revision, int) or isinstance(expected_revision, bool) or expected_revision < 0:
raise ValueError("revision is invalid")
normalized = self._normalize(views)
serialized = json.dumps(normalized, separators=(",", ":"))
with self._connect() as connection:
connection.execute("BEGIN IMMEDIATE")
row = connection.execute(
"SELECT revision, views FROM saved_searches WHERE login = ?", (login,)
).fetchone()
current = self._snapshot(row)
if current["revision"] != expected_revision:
raise SavedSearchConflict(current)
revision = expected_revision + 1
connection.execute(
"INSERT INTO saved_searches(login, revision, views) VALUES (?, ?, ?) "
"ON CONFLICT(login) DO UPDATE SET revision=excluded.revision, views=excluded.views",
(login, revision, serialized),
)
return {"revision": revision, "views": normalized}
+51 -3
View File
@@ -164,6 +164,44 @@ const fetchJson=async(url,options={{}})=>{{
assert output["second"]["confirmed"][0]["number"] == 469
def test_evidence_bundle_retry_resumes_at_failed_image_and_posts_one_ordered_comment():
script = f"""
const createBackgroundIssueSync=require({json.dumps(str(SYNC))});
let item={{id:'bundle',operationId:'bundle',ownerLogin:'timmy',status:'queued',repository:'o/r',title:'Journey',body:'',labelIds:[],attachments:[
{{filename:'one.png',contentType:'image/png',data:'b25l',note:'First state'}},
{{filename:'two.png',contentType:'image/png',data:'dHdv',note:'Tap [Submit](unsafe)'}},
{{filename:'three.png',contentType:'image/png',data:'dGhyZWU='}},
]}};
const calls=[];let twoAttempts=0;
const store={{claimNext:async()=>item?{{...item}}:null,update:async(_id,fn)=>{{item=fn(item);}},complete:async()=>{{item=null;}},release:async()=>{{item={{...item,status:'queued'}};}},fail:async()=>{{}},countBlocked:async()=>0}};
const fetchJson=async(url,options={{}})=>{{
if(url==='api/v1/background-identity')return{{login:'timmy'}};
let filename=null;if(options.body instanceof FormData)filename=options.body.get('file').name;
calls.push({{url,key:options.headers?.['Idempotency-Key'],filename,body:options.body instanceof FormData?null:JSON.parse(options.body)}});
if(url.endsWith('/issues'))return{{number:823}};
if(url.endsWith('/attachments')){{if(filename==='two.png' && twoAttempts++===0){{const e=new Error('offline');e.status=503;throw e;}}return{{markdown:'!['+filename+'](url/'+filename+')'}};}}
return{{id:9}};
}};
(async()=>{{const sync=createBackgroundIssueSync({{store,fetchJson}});let first='';try{{await sync.flush();}}catch(e){{first=e.message;}}const checkpoint={{...item}};await sync.flush();process.stdout.write(JSON.stringify({{first,checkpoint,calls}}));}})();
"""
output = run_node(script)
assert output["first"] == "offline"
uploads = [call for call in output["calls"] if call["filename"]]
assert [call["filename"] for call in uploads] == ["one.png", "two.png", "two.png", "three.png"]
assert [call["key"] for call in uploads] == [
"bundle:attachment-0", "bundle:attachment-1", "bundle:attachment-1", "bundle:attachment-2"
]
assert output["checkpoint"]["attachmentMarkdowns"] == ["![one.png](url/one.png)"]
comments = [call for call in output["calls"] if call["url"].endswith("/comments")]
assert len(comments) == 1
assert comments[0]["body"]["body"].split("\n\n") == [
"**Screenshot 1 — First state**", "![one.png](url/one.png)",
"**Screenshot 2 — Tap \\[Submit\\]\\(unsafe\\)**", "![two.png](url/two.png)",
"![three.png](url/three.png)"
]
def test_closed_app_sync_uploads_blob_as_multipart_and_preserves_original_bytes():
script = f"""
const createBackgroundIssueSync=require({json.dumps(str(SYNC))});
@@ -633,22 +671,32 @@ const transaction=work=>{{const run=tail.then(()=>work({{
await store.reconcile([{{
id:'first',operationId:'first',ownerLogin:'timmy',status:'queued',
attachment:{{filename:'one.png',contentType:'image/png',blob:new Blob(['first-image-bytes'],{{type:'image/png'}})}},
}}]);
}},{{id:'bundle',operationId:'bundle',ownerLogin:'timmy',status:'queued',attachments:[
{{filename:'a.png',contentType:'image/png',blob:new Blob(['a-bytes'],{{type:'image/png'}})}},
{{filename:'b.png',contentType:'image/png',blob:new Blob(['b-bytes'],{{type:'image/png'}})}},
]}}]);
await store.reconcile([
{{id:'first',operationId:'first',ownerLogin:'timmy',status:'queued',
attachment:{{filename:'one.png',contentType:'image/png',stored:true}}}},
{{id:'second',operationId:'second',ownerLogin:'timmy',status:'queued',
attachment:{{filename:'two.png',contentType:'image/png',data:'c2Vjb25kLWltYWdlLWJ5dGVz'}}}},
{{id:'bundle',operationId:'bundle',ownerLogin:'timmy',status:'queued',attachments:[
{{filename:'a.png',contentType:'image/png',stored:true}},
{{filename:'b.png',contentType:'image/png',stored:true}},
]}},
]);
const snapshot=await store.snapshot();
process.stdout.write(JSON.stringify({{first:{{isBlob:snapshot[0].attachment.blob instanceof Blob,
text:await snapshot[0].attachment.blob?.text()}},second:snapshot[1].attachment.data}}));
const byId=Object.fromEntries(snapshot.map(value=>[value.id,value]));
process.stdout.write(JSON.stringify({{first:{{isBlob:byId.first.attachment.blob instanceof Blob,
text:await byId.first.attachment.blob?.text()}},second:byId.second.attachment.data,
bundle:await Promise.all(byId.bundle.attachments.map(value=>value.blob?.text()))}}));
}})();
"""
output = run_node(script)
assert output["first"] == {"isBlob": True, "text": "first-image-bytes"}
assert output["second"] == "c2Vjb25kLWltYWdlLWJ5dGVz"
assert output["bundle"] == ["a-bytes", "b-bytes"]
def test_issue_sync_store_hydrates_one_capture_by_key_without_scanning_all_records():
+49
View File
@@ -155,6 +155,55 @@ first.run([item]).then(firstResult=>{{
}
def test_interrupted_batch_restores_operation_context_for_idempotent_recovery():
script = f"""
const createBatchFindWork=require({json.dumps(str(BATCH_FIND_WORK))});
const values={{}};
const storage={{
getItem:key=>values[key] || null,
setItem:(key,value)=>{{values[key]=value;}},
removeItem:key=>{{delete values[key];}},
}};
const calls=[];
const options={{
capacity:()=>2, storage, owner:()=> 'timmy', journalName:'search-later-batch',
queueFailureReason:'assigned but Later could not be saved',
claim:item=>Promise.resolve({{...item,assigned_to_me:true}}),
}};
const first=createBatchFindWork({{...options, queue:(item,context)=>{{
calls.push(['first',item.number,context?.until]);
return item.number===813 ? 'queued' : 'unavailable';
}}}});
const items=[813,814].map(number=>({{repository:'stackchain/dashboard',number}}));
first.run(items, {{}}, {{until:'2026-08-15T09:00:00.000Z'}}).then(firstResult=>{{
const second=createBatchFindWork({{...options, queue:(item,context)=>{{
calls.push(['resume',item.number,context?.until]);
return 'queued';
}}}});
return second.resume().then(resumed=>process.stdout.write(JSON.stringify({{
firstResult,resumed,calls,keys:Object.keys(values),
}})));
}});
"""
result = run_node(script)
assert result["firstResult"]["queued"] == ["stackchain/dashboard#813"]
assert result["firstResult"]["failed"] == [{
"key": "stackchain/dashboard#814",
"reason": "assigned but Later could not be saved",
"assigned": True,
}]
assert result["resumed"]["queued"] == [
"stackchain/dashboard#813", "stackchain/dashboard#814",
]
assert result["calls"] == [
["first", 813, "2026-08-15T09:00:00.000Z"],
["first", 814, "2026-08-15T09:00:00.000Z"],
["resume", 814, "2026-08-15T09:00:00.000Z"],
]
assert result["keys"] == []
def test_resumed_batch_skips_queued_items_and_continues_in_original_order():
script = f"""
const createBatchFindWork=require({json.dumps(str(BATCH_FIND_WORK))});
+2 -2
View File
@@ -74,8 +74,8 @@ def test_product_workflows_are_stable_lazy_feature_chunks(tmp_path):
assert b"function createQueueToday" in first.feature_bundles["today-timer"].runtime_bytes
assert b"gitea_time_logged" not in first.runtime_bytes
assert b"gitea_time_logged" in security_center.runtime_bytes
# Core mobile workflows stay below 98 KiB gzip, including transaction-safe Update decisions.
assert len(first.runtime_gzip_bytes) <= 98 * 1024
# Core mobile workflows stay below 99 KiB, including synced Search views and Update decisions.
assert len(first.runtime_gzip_bytes) <= 99 * 1024
assert f'name="stackchain-feature-issue-capture" content="{capture.runtime_name}"' in first.dashboard_html
assert f'name="stackchain-feature-pull-workflow" content="{pull_workflow.runtime_name}"' in first.dashboard_html
assert f"BASE + '{capture.runtime_name}'" in first.service_worker_source
+75
View File
@@ -215,6 +215,81 @@ async def test_gitea_milestone_update_revalidates_assignment_and_open_repository
}
@pytest.mark.anyio
@pytest.mark.parametrize("due_date", ["2026-08-31T23:59:59Z", None])
async def test_release_plan_applies_milestone_and_optional_deadline_in_one_patch(due_date):
requests = []
existing_due_date = "2026-08-20T23:59:59Z"
async def handler(request):
requests.append(request)
if request.url.path == "/api/v1/user":
return httpx.Response(200, json={"login": "timmy"})
if request.method == "GET" and request.url.path.endswith("/issues/17"):
return httpx.Response(200, json={
"number": 17, "state": "open", "pull_request": None,
"assignees": [{"login": "timmy"}], "due_date": existing_due_date,
})
if request.method == "GET" and request.url.path.endswith("/milestones"):
return httpx.Response(200, json=[
{"id": 9, "title": "August RC", "state": "open"},
])
return httpx.Response(200, json={
"number": 17, "state": "open",
"milestone": {"id": 9, "title": "August RC"},
"due_date": due_date or existing_due_date,
})
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
try:
result = await gitea_proxy.update_assigned_issue_release_plan(
"stackchain/api", 17, 9, due_date
)
finally:
await gitea_proxy.stop_client()
patch_requests = [request for request in requests if request.method == "PATCH"]
assert len(patch_requests) == 1
expected_payload = {"milestone": 9}
if due_date:
expected_payload["due_date"] = due_date
assert json.loads(patch_requests[0].content) == expected_payload
assert result == {
"repository": "stackchain/api", "number": 17, "state": "open",
"milestone": {"id": 9, "title": "August RC"},
"due_date": due_date or existing_due_date,
}
@pytest.mark.anyio
async def test_release_plan_endpoint_is_bounded_and_returns_confirmed_plan(monkeypatch):
calls = []
async def update(repository, number, milestone_id, due_date):
calls.append((repository, number, milestone_id, due_date))
return {
"repository": repository, "number": number, "state": "open",
"milestone": {"id": milestone_id, "title": "August RC"},
"due_date": due_date,
}
monkeypatch.setattr(
main.gitea_proxy, "update_assigned_issue_release_plan", update, raising=False
)
transport = httpx.ASGITransport(app=main.app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
response = await client.patch(
"/api/v1/repos/stackchain/api/issues/17/release-plan",
json={"milestone_id": 9, "due_date": "2026-08-31T23:59:59Z"},
)
assert response.status_code == 200
assert response.headers["cache-control"] == "no-store"
assert response.json()["milestone"] == {"id": 9, "title": "August RC"}
assert response.json()["due_date"] == "2026-08-31T23:59:59Z"
assert calls == [("stackchain/api", 17, 9, "2026-08-31T23:59:59Z")]
@pytest.mark.anyio
async def test_milestone_routes_are_repository_bounded_and_no_store(monkeypatch):
calls = []
+257 -9
View File
@@ -58,6 +58,95 @@ controller.select(file);
}
def test_mobile_evidence_bundle_keeps_order_limits_selection_and_uploads_each_image_once():
script = f"""
const attachment = require({json.dumps(str(ATTACHMENT))});
let sequence=0; const calls=[];
const image=name=>{{const blob=new Blob([name],{{type:'image/png'}});blob.name=name;return blob;}};
const controller=attachment.create({{
maxFiles:5,
createOperationId:()=> 'evidence-' + (++sequence),
upload:async payload=>{{calls.push([payload.filename,payload.operation_id]);return {{markdown:'!['+payload.filename+'](url/'+payload.filename+')'}};}},
}});
for(const name of ['one.png','two.png','three.png','four.png','five.png']) controller.select(image(name));
let limit='';try{{controller.select(image('six.png'));}}catch(error){{limit=error.message;}}
controller.remove(1);
controller.select(image('replacement.png'));
(async()=>{{
const serialized=await controller.serialize();
const comment=await controller.prepareComment({{repository:'o/r',number:823}},'Evidence sequence');
const second=await controller.prepareComment({{repository:'o/r',number:823}},'Evidence sequence');
process.stdout.write(JSON.stringify({{limit,state:controller.state(),names:serialized.map(x=>x.filename),comment,second,calls}}));
}})().catch(error=>{{console.error(error);process.exit(1);}});
"""
output = json.loads(run_node(script))
assert output["limit"] == "Up to 5 screenshots. Remove one before adding another."
assert output["names"] == ["one.png", "three.png", "four.png", "five.png", "replacement.png"]
assert [item["name"] for item in output["state"]] == output["names"]
assert output["comment"] == output["second"]
assert output["comment"].startswith("Evidence sequence\n\n![one.png]")
assert len(output["calls"]) == 5
assert len({key for _, key in output["calls"]}) == 5
def test_mobile_evidence_bundle_reorders_selected_image_for_serialization_and_upload():
script = f"""
const attachment = require({json.dumps(str(ATTACHMENT))});
const uploaded=[];
const image=name=>{{const blob=new Blob([name],{{type:'image/png'}});blob.name=name;return blob;}};
const controller=attachment.create({{
maxFiles:5,
upload:async payload=>{{uploaded.push(payload.filename);return {{markdown:'!['+payload.filename+'](url)'}};}},
}});
['one.png','two.png','three.png'].forEach(name=>controller.select(image(name)));
controller.move(2, 0);
controller.move(0, 99);
controller.move(0, 1);
(async()=>{{
const serialized=await controller.serialize();
const comment=await controller.prepareComment({{repository:'o/r',number:825}},'Reviewed');
process.stdout.write(JSON.stringify({{names:serialized.map(x=>x.filename),uploaded,comment}}));
}})().catch(error=>{{console.error(error);process.exit(1);}});
"""
output = json.loads(run_node(script))
assert output["names"] == ["one.png", "three.png", "two.png"]
assert output["uploaded"] == output["names"]
assert output["comment"].endswith(
"![one.png](url)\n\n![three.png](url)\n\n![two.png](url)"
)
def test_mobile_evidence_notes_follow_images_and_render_as_safe_ordered_captions():
script = f"""
const attachment = require({json.dumps(str(ATTACHMENT))});
const image=name=>{{const blob=new Blob([name],{{type:'image/png'}});blob.name=name;return blob;}};
const controller=attachment.create({{
maxFiles:5,
upload:async payload=>({{markdown:'!['+payload.filename+'](url/'+payload.filename+')'}}),
}});
['one.png','two.png','three.png'].forEach(name=>controller.select(image(name)));
controller.setNote(0, ' Login *token* is visible ');
controller.setNote(1, 'Keyboard hides [Submit](bad)');
controller.setNote(2, '');
controller.move(1, 0);
controller.remove(1);
(async()=>{{
const serialized=await controller.serialize();
const comment=await controller.prepareComment({{repository:'o/r',number:827}},'Evidence');
process.stdout.write(JSON.stringify({{serialized:serialized.map(x=>({{filename:x.filename,note:x.note||''}})),comment}}));
}})().catch(error=>{{console.error(error);process.exit(1);}});
"""
output = json.loads(run_node(script))
assert output["serialized"] == [
{"filename": "two.png", "note": "Keyboard hides [Submit](bad)"},
{"filename": "three.png", "note": ""},
]
assert output["comment"] == (
"Evidence\n\n**Screenshot 1 — Keyboard hides \\[Submit\\]\\(bad\\)**\n\n"
"![two.png](url/two.png)\n\n![three.png](url/three.png)"
)
def test_mobile_attachment_retry_reuses_operation_key_until_file_changes():
script = f"""
const attachment = require({json.dumps(str(ATTACHMENT))});
@@ -224,6 +313,120 @@ controller.restore({{filename:'saved.png',contentType:'image/png',data:'iVBORw0K
assert output["removed"] is None
def test_attachment_view_restores_ordered_evidence_bundle_preview():
script = f"""
const attachment=require({json.dumps(str(ATTACHMENT))});
class Element{{constructor(){{this.listeners={{}};this.hidden=true;this.value='';this.textContent='';this.src='';this.disabled=false;}}addEventListener(t,f){{this.listeners[t]=f;}}}}
const input=new Element(),preview=new Element(),image=new Element(),meta=new Element(),remove=new Element(),status=new Element();input.multiple=true;
const controller=attachment.mount({{input,preview,image,meta,remove,status,createObjectURL:blob=>'blob:'+blob.size,revokeObjectURL:()=>{{}},upload:async()=>{{}}}});
const value=name=>({{filename:name,contentType:'image/png',blob:new Blob([name],{{type:'image/png'}})}});
const restored=controller.restore([value('one.png'),value('two.png')]);
process.stdout.write(JSON.stringify({{restored,src:image.src,meta:meta.textContent,hidden:preview.hidden}}));
"""
output = json.loads(run_node(script))
assert [item["name"] for item in output["restored"]] == ["one.png", "two.png"]
assert output["src"] == "blob:7"
assert output["meta"] == "2 screenshots ready · latest: two.png"
assert output["hidden"] is False
def test_evidence_review_tray_selects_reorders_and_removes_any_screenshot():
script = f"""
const attachment=require({json.dumps(str(ATTACHMENT))});
class Element{{
constructor(tag='div'){{this.tag=tag;this.listeners={{}};this.children=[];this.hidden=true;this.value='';this.files=[];this.textContent='';this.src='';this.disabled=false;this.attributes={{}};this.dataset={{}};}}
addEventListener(type,fn){{this.listeners[type]=fn;}}
dispatch(type){{return this.listeners[type]({{target:this}});}}
appendChild(child){{this.children.push(child);return child;}}
replaceChildren(...children){{this.children=children;}}
setAttribute(name,value){{this.attributes[name]=String(value);}}
}}
const document={{createElement:tag=>new Element(tag)}};
const input=new Element('input'),preview=new Element(),image=new Element('img'),meta=new Element(),remove=new Element('button'),status=new Element(),tray=new Element(),earlier=new Element('button'),later=new Element('button');
input.multiple=true;
const urls=[];
const controller=attachment.mount({{input,preview,image,meta,remove,status,tray,earlier,later,document,
removedMessage:'Screenshot removed. Your issue draft is unchanged.',
createObjectURL:blob=>{{const url='blob:'+blob.name;urls.push(url);return url;}},revokeObjectURL:()=>{{}},upload:async()=>{{}}}});
const file=name=>{{const blob=new Blob([name],{{type:'image/png'}});blob.name=name;return blob;}};
input.files=['one.png','two.png','three.png'].map(file);
(async()=>{{
await input.dispatch('change');
await tray.children[1].dispatch('click');
await earlier.dispatch('click');
const reordered=(await controller.serialize()).map(item=>item.filename);
await remove.dispatch('click');
const remaining=(await controller.serialize()).map(item=>item.filename);
process.stdout.write(JSON.stringify({{reordered,remaining,preview:image.src,meta:meta.textContent,
selected:tray.children.map(button=>button.attributes['aria-pressed']),
labels:tray.children.map(button=>button.attributes['aria-label']),
earlierDisabled:earlier.disabled,laterDisabled:later.disabled,status:status.textContent}}));
}})().catch(error=>{{console.error(error);process.exit(1);}});
"""
output = json.loads(run_node(script))
assert output["reordered"] == ["two.png", "one.png", "three.png"]
assert output["remaining"] == ["one.png", "three.png"]
assert output["preview"] == "blob:one.png"
assert output["meta"] == "Screenshot 1 of 2 · one.png · 1 KB"
assert output["selected"] == ["true", "false"]
assert output["labels"] == [
"Review screenshot 1 of 2: one.png", "Review screenshot 2 of 2: three.png"
]
assert output["earlierDisabled"] is True
assert output["laterDisabled"] is False
assert output["status"] == "Screenshot removed. Your issue draft is unchanged."
def test_evidence_review_edits_the_active_note_and_keeps_it_visible_after_reorder():
script = f"""
const attachment=require({json.dumps(str(ATTACHMENT))});
class Element{{
constructor(tag='div'){{this.tag=tag;this.listeners={{}};this.children=[];this.hidden=true;this.value='';this.files=[];this.textContent='';this.src='';this.disabled=false;this.attributes={{}};}}
addEventListener(type,fn){{this.listeners[type]=fn;}}
dispatch(type){{return this.listeners[type]({{target:this}});}}
appendChild(child){{this.children.push(child);return child;}}
replaceChildren(...children){{this.children=children;}}
setAttribute(name,value){{this.attributes[name]=String(value);}}
}}
const document={{createElement:tag=>new Element(tag)}};
const input=new Element('input'),preview=new Element(),image=new Element('img'),meta=new Element(),remove=new Element('button'),status=new Element(),tray=new Element(),earlier=new Element('button'),later=new Element('button'),note=new Element('textarea'),noteLabel=new Element('label');
input.multiple=true;
const controller=attachment.mount({{input,preview,image,meta,remove,status,tray,earlier,later,note,noteLabel,document,
createObjectURL:blob=>'blob:'+blob.name,revokeObjectURL:()=>{{}},upload:async()=>{{}}}});
const file=name=>{{const blob=new Blob([name],{{type:'image/png'}});blob.name=name;return blob;}};
input.files=['one.png','two.png','three.png'].map(file);
(async()=>{{
await input.dispatch('change');
await tray.children[1].dispatch('click');
note.value='Keyboard hides Submit';
await note.dispatch('input');
await earlier.dispatch('click');
const afterMove={{value:note.value,label:noteLabel.textContent,disabled:note.disabled}};
await tray.children[1].dispatch('click');
const other={{value:note.value,label:noteLabel.textContent}};
process.stdout.write(JSON.stringify({{afterMove,other,serialized:(await controller.serialize()).map(x=>[x.filename,x.note||''])}}));
}})().catch(error=>{{console.error(error);process.exit(1);}});
"""
output = json.loads(run_node(script))
assert output == {
"afterMove": {
"value": "Keyboard hides Submit",
"label": "Evidence note for screenshot 1 of 3 (optional)",
"disabled": False,
},
"other": {
"value": "",
"label": "Evidence note for screenshot 2 of 3 (optional)",
},
"serialized": [
["two.png", "Keyboard hides Submit"],
["one.png", ""],
["three.png", ""],
],
}
def test_metadata_only_attachment_cannot_render_as_an_empty_screenshot():
script = f"""
const attachment=require({json.dumps(str(ATTACHMENT))});
@@ -264,13 +467,36 @@ def test_new_issue_sheet_captures_screenshot_into_durable_outbox():
assert 'id="create-issue-attachment"' in html
assert 'accept="image/png,image/jpeg,image/webp"' in html
assert 'multiple' in html
assert 'Up to 5' in html
assert 'id="create-issue-attachment-preview"' in html
assert 'id="remove-create-issue-attachment"' in html
assert 'id="create-issue-evidence-tray"' in html
assert 'role="toolbar"' in html
assert 'aria-label="Evidence screenshots"' in html
assert 'id="move-create-issue-attachment-earlier"' in html
assert 'id="move-create-issue-attachment-later"' in html
assert 'id="create-issue-evidence-note-label"' in html
assert 'id="create-issue-evidence-note"' in html
assert 'maxlength="240"' in html
assert "tray: qs('#create-issue-evidence-tray')" in source
assert "earlier: qs('#move-create-issue-attachment-earlier')" in source
assert "later: qs('#move-create-issue-attachment-later')" in source
assert "note: qs('#create-issue-evidence-note')" in source
assert "noteLabel: qs('#create-issue-evidence-note-label')" in source
assert "const createIssueAttachmentController = issueAttachment.mount({" in source
assert "attachment: await createIssueAttachmentController.serialize()" in source
assert "createIssueAttachmentController.restore(hydrated.attachment);" in source
assert "attachments:evidence" in source
assert "hydrated.attachments || hydrated.attachment" in source
assert "createIssueAttachmentController.clear();" in source
assert ".create-issue-attachment" in css
assert ".issue-evidence-tray" in css
assert ".issue-evidence-review-actions" in css
assert ".issue-evidence-note" in css
assert "resize:vertical" in css
assert "#create-issue-attachment-preview { grid-template-columns:1fr;" in css
assert "#create-issue-attachment-image { grid-row:auto; width:100%;" in css
assert "overflow-x:auto" in css
assert "min-width:44px" in css
assert "overflow-x:hidden" in css
@@ -410,21 +636,38 @@ def test_pending_comment_admission_locks_attachment_replacement_and_remove_contr
script = f"""
const attachment=require({json.dumps(str(ATTACHMENT))});
class Element {{
constructor() {{ this.listeners={{}};this.hidden=true;this.value='';this.files=[];this.textContent='';this.src='';this.disabled=false; }}
constructor() {{ this.listeners={{}};this.children=[];this.hidden=true;this.value='';this.files=[];this.textContent='';this.src='';this.disabled=false;this.attributes={{}}; }}
addEventListener(type,fn) {{ this.listeners[type]=fn; }}
appendChild(child) {{ this.children.push(child); }}
replaceChildren(...children) {{ this.children=children; }}
setAttribute(name,value) {{ this.attributes[name]=String(value); }}
}}
const input=new Element(),preview=new Element(),image=new Element(),meta=new Element(),remove=new Element(),status=new Element();
const controller=attachment.mount({{input,preview,image,meta,remove,status,
const input=new Element(),preview=new Element(),image=new Element(),meta=new Element(),remove=new Element(),status=new Element(),tray=new Element(),earlier=new Element(),later=new Element();
input.multiple=true;
const document={{createElement:()=>new Element()}};
const controller=attachment.mount({{input,preview,image,meta,remove,status,tray,earlier,later,document,
createObjectURL:()=> 'blob:preview',revokeObjectURL:()=>{{}},upload:async()=>{{}}}});
controller.restore([
{{filename:'one.png',contentType:'image/png',blob:new Blob(['one'],{{type:'image/png'}})}},
{{filename:'two.png',contentType:'image/png',blob:new Blob(['two'],{{type:'image/png'}})}},
]);
controller.setBusy(true);
const pending={{input:input.disabled,remove:remove.disabled}};
const pending={{input:input.disabled,remove:remove.disabled,earlier:earlier.disabled,later:later.disabled,
thumbnails:tray.children.map(button=>button.disabled)}};
controller.setBusy(false);
process.stdout.write(JSON.stringify({{pending,released:{{input:input.disabled,remove:remove.disabled}}}}));
process.stdout.write(JSON.stringify({{pending,released:{{input:input.disabled,remove:remove.disabled,
earlier:earlier.disabled,later:later.disabled,thumbnails:tray.children.map(button=>button.disabled)}}}}));
"""
assert json.loads(run_node(script)) == {
"pending": {"input": True, "remove": True},
"released": {"input": False, "remove": False},
"pending": {
"input": True, "remove": True, "earlier": True, "later": True,
"thumbnails": [True, True],
},
"released": {
"input": False, "remove": False, "earlier": False, "later": True,
"thumbnails": [False, False],
},
}
@@ -462,6 +705,11 @@ def test_readme_documents_mobile_screenshot_limits_and_delivery_order():
assert "uploads before the comment is posted" in readme
assert "New issue" in readme
assert "retry resumes with the confirmed issue" in readme
assert "thumbnail tray" in readme
assert "Move earlier" in readme
assert "Remove selected" in readme
assert "Evidence note" in readme
assert "caption" in readme
def test_issue_screenshot_comments_queue_serialized_bytes_before_clearing_or_advancing():
+153
View File
@@ -0,0 +1,153 @@
import json
import subprocess
from pathlib import Path
ROOT = Path(__file__).parents[1]
EDITOR = ROOT / "frontend" / "issue-evidence-editor.js"
ATTACHMENT = ROOT / "frontend" / "issue-attachment.js"
INDEX = ROOT / "frontend" / "index.html"
CSS = ROOT / "frontend" / "dashboard.css"
SERVICE_WORKER = ROOT / "frontend" / "service-worker.js"
def run_node(script: str) -> dict:
return json.loads(subprocess.run(
["node", "-e", script], check=True, capture_output=True, text=True
).stdout)
def test_editor_crops_redacts_undoes_and_flattens_derivative():
script = f"""
const editor = require({json.dumps(str(EDITOR))});
const model = editor.createModel({{width:400,height:300}});
model.setCrop({{x:40,y:30,width:240,height:180}});
model.addRedaction({{x:70,y:60,width:80,height:40}});
model.addRedaction({{x:180,y:120,width:50,height:30}});
model.undo();
const calls=[];
const canvas={{width:0,height:0,getContext:()=>({{
drawImage:(...args)=>calls.push(['draw',...args.slice(1)]),
fillRect:(...args)=>calls.push(['fill',...args]),
set fillStyle(value){{calls.push(['color',value]);}}
}}),toBlob:(callback,type)=>callback(new Blob(['flattened'],{{type}}))}};
(async()=>{{
const result=await editor.flatten({{source:{{}},model,canvas,name:'private.png',type:'image/png'}});
process.stdout.write(JSON.stringify({{snapshot:model.snapshot(),calls,width:canvas.width,height:canvas.height,
name:result.name,type:result.type,text:await result.text()}}));
}})().catch(error=>{{console.error(error);process.exit(1);}});
"""
output = run_node(script)
assert output["snapshot"] == {
"crop": {"x": 40, "y": 30, "width": 240, "height": 180},
"redactions": [{"x": 70, "y": 60, "width": 80, "height": 40}],
"annotations": [],
}
assert output["width"] == 240
assert output["height"] == 180
assert output["calls"] == [
["draw", 40, 30, 240, 180, 0, 0, 240, 180],
["color", "#000000"],
["fill", 30, 30, 80, 40],
]
assert output["name"] == "private.png"
assert output["type"] == "image/png"
assert output["text"] == "flattened"
def test_applying_edit_replaces_only_selected_blob_and_preserves_note_and_order():
script = f"""
const attachment=require({json.dumps(str(ATTACHMENT))});
let id=0;
const image=name=>{{const blob=new Blob([name],{{type:'image/png'}});blob.name=name;return blob;}};
const controller=attachment.create({{maxFiles:5,createOperationId:()=>`edit-${{++id}}`,upload:async()=>({{markdown:'ok'}})}});
['one.png','private.png','three.png'].forEach(name=>controller.select(image(name)));
controller.setNote(1,'Token hidden here');
controller.replace(1,image('private-edited.png'));
(async()=>{{
const values=await controller.serialize();
process.stdout.write(JSON.stringify({{values:await Promise.all(values.map(async value=>({{name:value.filename,note:value.note||'',text:await value.blob.text()}}))),state:controller.state()}}));
}})().catch(error=>{{console.error(error);process.exit(1);}});
"""
output = run_node(script)
assert output["values"] == [
{"name": "one.png", "note": "", "text": "one.png"},
{"name": "private-edited.png", "note": "Token hidden here", "text": "private-edited.png"},
{"name": "three.png", "note": "", "text": "three.png"},
]
assert [item["uploaded"] for item in output["state"]] == [False, False, False]
def test_editor_adds_undoes_and_flattens_highlight_and_arrow_annotations():
script = f"""
const editor = require({json.dumps(str(EDITOR))});
const model = editor.createModel({{width:400,height:300}});
model.setCrop({{x:40,y:30,width:240,height:180}});
model.addHighlight({{x:60,y:50,width:100,height:60}});
model.addArrow({{startX:80,startY:150,endX:220,endY:80}});
const beforeUndo=model.snapshot();
model.undo();
const afterUndo=model.snapshot();
model.addArrow({{startX:80,startY:150,endX:220,endY:80}});
const calls=[];
const context={{
drawImage:()=>calls.push(['draw']), fillRect:(...args)=>calls.push(['fill',...args]),
save:()=>calls.push(['save']), restore:()=>calls.push(['restore']),
beginPath:()=>calls.push(['begin']), moveTo:(...args)=>calls.push(['move',...args]),
lineTo:(...args)=>calls.push(['line',...args]), stroke:()=>calls.push(['stroke']),
set fillStyle(value){{calls.push(['fillStyle',value]);}},
set strokeStyle(value){{calls.push(['strokeStyle',value]);}},
set lineWidth(value){{calls.push(['lineWidth',value]);}},
set lineCap(value){{calls.push(['lineCap',value]);}},
set lineJoin(value){{calls.push(['lineJoin',value]);}},
}};
const canvas={{width:0,height:0,getContext:()=>context}};
editor.paint({{source:{{}},model,canvas}});
process.stdout.write(JSON.stringify({{beforeUndo,afterUndo,calls}}));
"""
output = run_node(script)
assert [item["type"] for item in output["beforeUndo"]["annotations"]] == ["highlight", "arrow"]
assert [item["type"] for item in output["afterUndo"]["annotations"]] == ["highlight"]
assert ["fillStyle", "rgba(250, 204, 21, 0.38)"] in output["calls"]
assert ["fill", 20, 20, 100, 60] in output["calls"]
assert ["strokeStyle", "#facc15"] in output["calls"]
assert ["move", 40, 120] in output["calls"]
assert ["line", 180, 50] in output["calls"]
assert output["calls"].count(["stroke"]) == 1
def test_crop_clips_annotations_to_the_retained_image_area():
script = f"""
const editor = require({json.dumps(str(EDITOR))});
const model = editor.createModel({{width:300,height:200}});
model.addHighlight({{x:20,y:30,width:100,height:80}});
model.addArrow({{startX:10,startY:90,endX:120,endY:90}});
model.setCrop({{x:50,y:20,width:100,height:120}});
process.stdout.write(JSON.stringify(model.snapshot()));
"""
output = run_node(script)
assert output["annotations"] == [
{"type": "highlight", "x": 50, "y": 30, "width": 70, "height": 80},
{"type": "arrow", "startX": 50, "startY": 90, "endX": 120, "endY": 90},
]
def test_mobile_editor_dialog_is_accessible_touch_sized_and_available_offline():
html = INDEX.read_text()
css = CSS.read_text()
worker = SERVICE_WORKER.read_text()
assert 'id="edit-create-issue-attachment"' in html
assert 'id="issue-evidence-editor"' in html
assert 'role="dialog"' in html
assert 'aria-labelledby="issue-evidence-editor-heading"' in html
assert 'id="issue-evidence-editor-canvas"' in html
assert 'id="highlight-issue-evidence"' in html
assert 'id="arrow-issue-evidence"' in html
assert 'aria-label="Screenshot editing canvas. Drag to crop, redact, highlight, or point with an arrow."' in html
assert 'aria-pressed="true"' in html
assert "issue-evidence-editor.js" in worker
assert ".issue-evidence-editor" in css
assert "min-height:44px" in css
assert "max-width:100%" in css
assert "overflow-x:hidden" in css
+89
View File
@@ -71,6 +71,74 @@ process.stdout.write(JSON.stringify({{items:reloaded, stored:JSON.parse(values.g
assert output["stored"]["version"] == 3
def test_issue_outbox_preserves_bounded_ordered_evidence_bundle():
script = f"""
const createIssueOutbox=require({json.dumps(str(OUTBOX))});
const values=new Map();const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
const image=name=>({{filename:name,contentType:'image/png',data:name,note:'Explain '+name}});
const outbox=createIssueOutbox({{storage,getOwnerLogin:()=>'timmy',createOperationId:()=>'bundle'}});
const queued=outbox.enqueue({{repository:'o/r',title:'Journey',attachments:['one','two','three','four','five'].map(image)}});
let limit='';try{{outbox.enqueue({{repository:'o/r',title:'Too many',attachments:['1','2','3','4','5','6'].map(image)}});}}catch(error){{limit=error.message;}}
process.stdout.write(JSON.stringify({{queued,list:outbox.list(),limit}}));
"""
output = run_node(script)
assert [item["filename"] for item in output["queued"]["attachments"]] == [
"one", "two", "three", "four", "five"
]
assert output["list"][0]["attachments"] == output["queued"]["attachments"]
assert [item["note"] for item in output["queued"]["attachments"]] == [
"Explain one", "Explain two", "Explain three", "Explain four", "Explain five"
]
assert output["limit"] == "You can attach up to 5 screenshots."
def test_foreground_issue_delivery_posts_the_same_captioned_evidence_bundle():
script = f"""
const createIssueOutbox=require({json.dumps(str(OUTBOX))});
const values=new Map(),calls=[];
const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
const fetchJson=async(url,options={{}})=>{{
let body=null;
if(options.body instanceof FormData)body={{filename:options.body.get('file').name}};
else if(options.body)body=JSON.parse(options.body);
calls.push({{url,key:options.headers?.['Idempotency-Key'],body}});
if(url.endsWith('/issues'))return{{number:827}};
if(url.endsWith('/attachments'))return{{markdown:'!['+body.filename+'](url/'+body.filename+')'}};
return{{id:9}};
}};
let id=0;const outbox=createIssueOutbox({{storage,fetchJson,getOwnerLogin:()=>'timmy',createOperationId:()=> 'op-'+(++id)}});
const image=(name,note)=>({{filename:name,contentType:'image/png',data:'eA==',note}});
outbox.enqueue({{repository:'o/r',title:'Journey',attachments:[image('one.png','First'),image('two.png','Tap *Submit*')]}});
(async()=>{{const result=await outbox.flush('timmy');process.stdout.write(JSON.stringify({{result,calls}}));}})();
"""
output = run_node(script)
assert output["result"]["confirmed"][0]["number"] == 827
uploads = [call for call in output["calls"] if call["url"].endswith("/attachments")]
assert [call["body"]["filename"] for call in uploads] == ["one.png", "two.png"]
comments = [call for call in output["calls"] if call["url"].endswith("/comments")]
assert len(comments) == 1
assert comments[0]["body"]["body"] == (
"**Screenshot 1 — First**\n\n![one.png](url/one.png)\n\n"
"**Screenshot 2 — Tap \\*Submit\\***\n\n![two.png](url/two.png)"
)
def test_issue_outbox_replaces_evidence_bundle_when_editing_a_queued_issue():
script = f"""
const createIssueOutbox=require({json.dumps(str(OUTBOX))});const values=new Map();
const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};const image=name=>({{filename:name,contentType:'image/png',data:name}});
let sequence=0;const outbox=createIssueOutbox({{storage,getOwnerLogin:()=>'timmy',createOperationId:()=>String(++sequence)}});
const queued=outbox.enqueue({{repository:'o/r',title:'Journey',attachments:[image('old-one'),image('old-two')]}});
const updated=outbox.update(queued.id,{{...queued,attachments:[image('new-one'),image('new-two'),image('new-three')]}});
process.stdout.write(JSON.stringify(updated));
"""
output = run_node(script)
assert [item["filename"] for item in output["attachments"]] == ["new-one", "new-two", "new-three"]
assert output["operationId"] != output["id"]
def test_issue_outbox_persists_a_validated_screenshot_with_the_capture():
script = f"""
const createIssueOutbox = require({json.dumps(str(OUTBOX))});
@@ -94,6 +162,27 @@ process.stdout.write(JSON.stringify(createIssueOutbox({{storage}}).list()[0]));
}
def test_issue_outbox_hydrates_durable_evidence_bundle_without_copying_blobs_to_localstorage():
script = f"""
const createIssueOutbox=require({json.dumps(str(OUTBOX))});
const values=new Map();const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
const image=name=>({{filename:name,contentType:'image/png',blob:new Blob([name],{{type:'image/png'}})}});
let durable=null;
const outbox=createIssueOutbox({{storage,getOwnerLogin:()=>'timmy',createOperationId:()=>'bundle',backgroundSync:{{
reconcile:async items=>{{durable=items[0];}},requestSync:async()=>{{}},get:async()=>durable,
}}}});
(async()=>{{const admitted=await outbox.enqueueDurably({{repository:'o/r',title:'Journey',attachments:['one','two'].map(image)}});
const raw=values.get('stackchain.issue-outbox.v1');const hydrated=await outbox.hydrateForEdit(admitted.item.id);
process.stdout.write(JSON.stringify({{raw,names:hydrated.attachments.map(x=>x.filename),sizes:hydrated.attachments.map(x=>x.blob.size)}}));}})();
"""
output = run_node(script)
assert '"stored":true' in output["raw"]
assert '"blob"' not in output["raw"]
assert output["names"] == ["one", "two"]
assert output["sizes"] == [3, 3]
def test_issue_outbox_hydrates_a_metadata_only_screenshot_for_edit_without_copying_bytes_to_localstorage():
script = f"""
const createIssueOutbox = require({json.dumps(str(OUTBOX))});
+19
View File
@@ -132,3 +132,22 @@ process.stdout.write(JSON.stringify({{first, second, confirmations}}));
output = run_node(script)
assert output == {"first": True, "second": False, "confirmations": 1}
def test_picker_item_can_own_batch_confirmation_and_run_after_close():
script = f"""
const createLaterPicker = require({json.dumps(str(LATER_PICKER))});
const order=[];
const picker=createLaterPicker({{
now:() => new Date(2026,7,14,8,0),
onConfirm:()=>{{order.push('global');return true;}},
}});
picker.open({{confirm:until=>() => order.push(until.toISOString())}},null,'search-batch');
const saved=picker.submit('2026-08-15T09:00');
process.stdout.write(JSON.stringify({{saved,order}}));
"""
assert run_node(script) == {
"saved": True,
"order": ["2026-08-15T09:00:00.000Z"],
}
+3 -6
View File
@@ -325,11 +325,13 @@ async def test_live_snapshot_keeps_fresh_activity_when_work_fails(monkeypatch):
@pytest.mark.anyio
async def test_live_snapshot_reuses_completed_snapshot_inside_freshness_window(monkeypatch):
user_calls = 0
user_started = asyncio.Event()
release = asyncio.Event()
async def user():
nonlocal user_calls
user_calls += 1
user_started.set()
return {"id": 1, "login": "timmy"}
async def blocked_repos():
@@ -350,13 +352,8 @@ async def test_live_snapshot_reuses_completed_snapshot_inside_freshness_window(m
monkeypatch.setattr(main, "notifications", empty)
first = asyncio.create_task(main.live_snapshot())
await asyncio.sleep(0)
await user_started.wait()
second = asyncio.create_task(main.live_snapshot())
for _ in range(100):
if user_calls:
break
await asyncio.to_thread(lambda: None)
assert user_calls == 1
release.set()
await asyncio.gather(first, second)
+95
View File
@@ -0,0 +1,95 @@
import httpx
import pytest
from src import main
from src.saved_search_store import SavedSearchConflict, SavedSearchStore
def view(view_id="release", name="Release queue", query="mobile", **scope):
return {
"id": view_id,
"name": name,
"query": query,
"kind": scope.get("kind", "issue"),
"state": scope.get("state", "open"),
"repository": scope.get("repository", "stackchain/stackchain-dashboard"),
}
def test_saved_searches_are_revisioned_ordered_and_account_scoped(tmp_path):
store = SavedSearchStore(tmp_path / "saved-searches.sqlite3")
created = store.replace(" Timmy ", 0, [view(), view("reviews", "My reviews", "review", kind="pull")])
assert created == {"revision": 1, "views": [view(), view("reviews", "My reviews", "review", kind="pull")]}
assert store.get("timmy") == created
assert store.get("alexander") == {"revision": 0, "views": []}
with pytest.raises(SavedSearchConflict) as conflict:
store.replace("timmy", 0, [view(name="Stale overwrite")])
assert conflict.value.snapshot == created
def test_saved_searches_validate_and_bound_the_synced_collection(tmp_path):
store = SavedSearchStore(tmp_path / "saved-searches.sqlite3", limit=2)
with pytest.raises(ValueError, match="limited to 2"):
store.replace("timmy", 0, [view("one"), view("two"), view("three")])
with pytest.raises(ValueError, match="unique"):
store.replace("timmy", 0, [view("same"), view("same")])
invalid = [
({**view(), "name": " "}, "name is required"),
({**view(), "query": "x"}, "query must be between"),
({**view(), "kind": "commit"}, "kind is invalid"),
({**view(), "state": "merged"}, "state is invalid"),
({**view(), "repository": "not-a-repository"}, "repository is invalid"),
]
for candidate, message in invalid:
with pytest.raises(ValueError, match=message):
store.replace("timmy", 0, [candidate])
@pytest.mark.anyio
async def test_saved_search_api_is_authenticated_csrf_protected_no_store_and_conflict_safe(monkeypatch, tmp_path):
monkeypatch.setenv("STACKCHAIN_DASHBOARD_AUTH_MODE", "operator")
monkeypatch.setenv("STACKCHAIN_DASHBOARD_ACCESS_TOKEN", "correct horse battery staple")
monkeypatch.setenv(
"STACKCHAIN_DASHBOARD_SESSION_SECRET",
"a-separate-session-signing-secret-with-enough-entropy",
)
monkeypatch.setenv("STACKCHAIN_SESSION_DB", str(tmp_path / "sessions.sqlite3"))
monkeypatch.setenv("STACKCHAIN_LOGIN_ATTEMPT_DB", str(tmp_path / "login.sqlite3"))
monkeypatch.setenv("STACKCHAIN_SAVED_SEARCH_DB", str(tmp_path / "searches.sqlite3"))
async def user():
return {"id": 1, "login": "Timmy"}
monkeypatch.setattr(main, "current_user", user)
transport = httpx.ASGITransport(app=main.app)
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
await client.post("/api/v1/session", json={"access_token": "correct horse battery staple"})
forbidden = await client.put(
"/api/v1/saved-searches", json={"revision": 0, "views": [view()]}
)
headers = {"Origin": "https://test", "X-CSRF-Token": client.cookies["stackchain_csrf"]}
saved = await client.put(
"/api/v1/saved-searches", json={"revision": 0, "views": [view()]}, headers=headers
)
stale = await client.put(
"/api/v1/saved-searches",
json={"revision": 0, "views": [view(name="Overwrite")]},
headers=headers,
)
fetched = await client.get("/api/v1/saved-searches")
assert forbidden.status_code == 403
assert saved.status_code == 200
assert saved.json() == {"revision": 1, "views": [view()]}
assert stale.status_code == 409
assert stale.json()["detail"] == {
"message": "Saved searches changed on another device.",
"snapshot": saved.json(),
}
assert fetched.json() == saved.json()
assert fetched.headers["cache-control"] == "no-store"
+105
View File
@@ -0,0 +1,105 @@
import json
import subprocess
from pathlib import Path
SAVED_SEARCHES = Path(__file__).parents[1] / "frontend" / "saved-searches.js"
def run_node(script):
return json.loads(
subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True).stdout
)
def test_saved_search_controller_loads_saves_opens_renames_and_deletes():
script = f"""
const createSavedSearches=require({json.dumps(str(SAVED_SEARCHES))});
const requests=[]; const opened=[]; const states=[];
let remote={{revision:0,views:[]}}; let sequence=0;
const controller=createSavedSearches({{
fetchJson:async (_url,options={{}})=>{{
requests.push(options.method||'GET');
if(!options.method)return remote;
const body=JSON.parse(options.body);remote={{revision:remote.revision+1,views:body.views}};return remote;
}},
createId:()=> 'view-'+(++sequence),
onOpen:view=>opened.push(view),
onState:state=>states.push(state),
}});
(async()=>{{
await controller.load();
await controller.save('Release queue',{{query:'mobile',kind:'issue',state:'open',repository:'stackchain/dashboard'}});
controller.open('view-1');
await controller.rename('view-1','Morning release queue');
await controller.remove('view-1');
process.stdout.write(JSON.stringify({{requests,opened,snapshot:controller.snapshot(),statuses:states.map(x=>x.status)}}));
}})().catch(error=>{{console.error(error);process.exit(1)}});
"""
assert run_node(script) == {
"requests": ["GET", "PUT", "PUT", "PUT"],
"opened": [{
"id": "view-1",
"name": "Release queue",
"query": "mobile",
"kind": "issue",
"state": "open",
"repository": "stackchain/dashboard",
}],
"snapshot": {"revision": 3, "views": []},
"statuses": ["loading", "ready", "saving", "ready", "saving", "ready", "saving", "ready"],
}
def test_saved_search_controller_adopts_conflict_and_keeps_search_usable_on_failure():
script = f"""
const createSavedSearches=require({json.dumps(str(SAVED_SEARCHES))});
const states=[];let mode='conflict';
const server={{revision:4,views:[{{id:'remote',name:'Remote',query:'review',kind:'pull',state:'open',repository:''}}]}};
const controller=createSavedSearches({{
fetchJson:async (_url,options={{}})=>{{
if(!options.method)return {{revision:3,views:[]}};
if(mode==='conflict'){{const error=new Error('conflict');error.status=409;error.payload={{detail:{{snapshot:server}}}};throw error;}}
throw new Error('offline');
}},createId:()=> 'local',onOpen:()=>{{}},onState:state=>states.push([state.status,state.message||'']),
}});
(async()=>{{
await controller.load();
try{{await controller.save('Local',{{query:'mobile',kind:'all',state:'all'}})}}catch(_error){{}}
mode='offline';
try{{await controller.remove('remote')}}catch(_error){{}}
process.stdout.write(JSON.stringify({{snapshot:controller.snapshot(),states}}));
}})();
"""
result = run_node(script)
assert result["snapshot"] == {
"revision": 4,
"views": [{
"id": "remote", "name": "Remote", "query": "review",
"kind": "pull", "state": "open", "repository": "",
}],
}
assert result["states"][-1] == ["error", "Saved searches could not sync. Search still works."]
assert ["conflict", "Saved searches changed on another device."] in result["states"]
def test_mobile_search_renders_synced_saved_view_controls_and_runtime_wiring():
from tests.dashboard_bundle import dashboard_bundle_text
html = dashboard_bundle_text()
css = (SAVED_SEARCHES.parent / "dashboard.css").read_text()
dashboard = (SAVED_SEARCHES.parent / "dashboard.js").read_text()
assert '<section class="saved-searches" aria-labelledby="saved-searches-heading">' in html
assert 'id="saved-search-name"' in html
assert 'id="save-current-search"' in html
assert 'id="saved-search-list"' in html
assert 'id="saved-search-status"' in html
assert "createSavedSearches.mount(" in dashboard
saved_searches = SAVED_SEARCHES.read_text()
assert "search.setQuery('')" in saved_searches
assert "applyScope(view)" in saved_searches
assert "search.setQuery(view.query)" in saved_searches
assert ").load();" in dashboard
assert "static/saved-searches.js" in (SAVED_SEARCHES.parent.parent / "src" / "frontend_bundle.py").read_text()
assert ".saved-search-action { min-height:44px;" in css
+263 -1
View File
@@ -69,6 +69,20 @@ Promise.all([
assert result["results"][2] == "This issue is no longer available to assign."
def test_release_planning_requires_selected_issues_from_one_repository():
script = f"""
const createSearchBatchPlan=require({json.dumps(str(SEARCH_BATCH_PLAN))});
const flow=createSearchBatchPlan();
flow.start();
flow.toggle({{kind:'issue',state:'open',repository:'stackchain/dashboard',number:815}});
const one=flow.releaseRepository();
flow.toggle({{kind:'issue',state:'open',repository:'stackchain/api',number:17}});
process.stdout.write(JSON.stringify({{one,mixed:flow.releaseRepository()}}));
"""
assert run_node(script) == {"one": "stackchain/dashboard", "mixed": None}
def test_mobile_search_exposes_touch_safe_durable_batch_planning_controls():
html = HTML.read_text()
dashboard = DASHBOARD.read_text()
@@ -79,13 +93,25 @@ def test_mobile_search_exposes_touch_safe_durable_batch_planning_controls():
assert 'id="select-search-results"' in html
assert 'id="search-batch-actions"' in html
assert 'id="queue-selected-search-results"' in html
assert 'id="defer-selected-search-results"' in html
assert 'id="plan-selected-search-results"' in html
assert 'id="search-release-review"' in html
assert 'id="search-release-milestone"' in html
assert 'id="search-release-due-date"' in html
assert 'id="resume-search-batch"' in html
assert 'src="static/search-batch-plan.js"' in html
assert "mountSearchBatchPlanning(" in dashboard
assert "escapeHtml, escAttr, laterWork, laterPicker" in dashboard
assert "journalName:'search-today-batch'" in controller
assert "journalName:'search-later-batch'" in controller
assert "journalName:'search-release-batch'" in controller
assert "autoMount:false" in controller
assert "plan.toggle(result)" in controller
assert "processor.run(plan.snapshot().items)" in controller
assert "processor.run(plan.snapshot().items, estimateValues())" in controller
assert "timeBudget:()" in controller
assert "persistEstimate" in controller
assert 'id="search-batch-estimate-review"' in html
assert 'data-search-batch-estimate' in controller
assert "processor.resume()" in controller
assert 'aria-label="Select ' in controller
assert "result.kind === 'issue' && result.state === 'open'" in controller
@@ -93,4 +119,240 @@ def test_mobile_search_exposes_touch_safe_durable_batch_planning_controls():
assert "position:sticky" in css
assert "env(safe-area-inset-bottom)" in css
assert ".cmd-select-result" in css and "min-height:44px" in css
assert ".search-release-review" in css and "100dvh" in css
assert ".search-release-actions" in css and "env(safe-area-inset-bottom)" in css
assert "BASE + 'static/search-batch-plan.js'" in worker
def test_selected_search_issues_choose_one_future_time_before_durable_batch_defer():
script = f"""
const createSearchBatchPlan=require({json.dumps(str(SEARCH_BATCH_PLAN))});
const listeners={{}};
const elements={{}};
for (const id of [
'search-batch-actions','select-search-results','queue-selected-search-results',
'defer-selected-search-results','plan-selected-search-results','search-selection-status','cmd-search-action-status',
'resume-search-batch','open-palette','cmd-results','cancel-search-selection',
'search-batch-estimate-review','search-batch-estimate-summary','search-batch-estimate-list',
'cancel-search-batch-estimates','confirm-search-batch-estimates','search-release-review',
'search-release-summary','search-release-milestone','search-release-due-date','search-release-list',
'cancel-search-release','confirm-search-release'
]) elements['#'+id]={{hidden:false,disabled:false,textContent:'',innerHTML:'',
addEventListener:(name,fn)=>listeners[id+':'+name]=fn,focus:()=>{{}}}};
const document={{querySelector:selector=>elements[selector] || null,querySelectorAll:()=>[]}};
const processorOptions=[];
const runs=[];
const processors=[];
const batchFactory=options=>{{
processorOptions.push(options);
const processor={{
run:(items,estimates,context)=>{{runs.push({{items,estimates,context}});return Promise.resolve();}},
resume:()=>Promise.resolve(),pending:()=>0,
}};
processors.push(processor);
return processor;
}};
const planning={{capacity_minutes:null,estimates:{{}}}};
const todayWork={{limit:8,read:()=>[],planning:()=>planning,identity:item=>item.repository+'#'+item.number,
replacePlanning:()=>{{}}}};
const laterCalls=[];
const laterWork={{defer:(item,until)=>{{laterCalls.push([item.number,until]);return 'deferred';}}}};
let pickerRequest=null;
const laterPicker={{open:(payload,trigger,context)=>{{pickerRequest={{payload,trigger,context}};return true;}}}};
const item={{kind:'issue',state:'open',repository:'stackchain/dashboard',number:813,title:'Batch defer'}};
const mounted=createSearchBatchPlan.mount(
document,batchFactory,todayWork,()=> 'timmy',()=>Promise.resolve(),()=>'',()=>Promise.resolve('queued'),
{{enqueueConfiguration:()=>{{}},flush:()=>{{}}}},value=>({{...value,accepted:true}}),()=>item,()=>{{}},
value=>value,value=>value,laterWork,laterPicker
);
mounted.plan.start();
mounted.plan.toggle(item);
listeners['defer-selected-search-results:click']({{currentTarget:elements['#defer-selected-search-results']}});
const before={{runs:runs.slice(),count:pickerRequest.payload.items.length,context:pickerRequest.context,journals:processorOptions.map(value=>value.journalName)}};
pickerRequest.payload.confirm(new Date('2026-08-15T09:00:00.000Z'))();
const laterResult=processorOptions[1].queue({{...item,assigned_to_me:true}},{{until:'2026-08-15T09:00:00.000Z'}});
process.stdout.write(JSON.stringify({{before,runs,laterResult,laterCalls}}));
"""
result = run_node(script)
assert result["before"] == {
"runs": [],
"count": 1,
"context": "search-batch",
"journals": ["search-today-batch", "search-later-batch", "search-release-batch"],
}
assert result["runs"] == [{
"items": [{
"kind": "issue", "state": "open", "repository": "stackchain/dashboard",
"number": 813, "title": "Batch defer",
}],
"estimates": {},
"context": {"until": "2026-08-15T09:00:00.000Z"},
}]
assert result["laterResult"] == "queued"
assert result["laterCalls"] == [[813, "2026-08-15T09:00:00.000Z"]]
def test_search_batch_reviews_time_estimates_before_any_assignment_and_persists_queued_estimates():
script = f"""
const createSearchBatchPlan=require({json.dumps(str(SEARCH_BATCH_PLAN))});
const listeners={{}};
const elements={{}};
for (const id of [
'search-batch-actions','select-search-results','queue-selected-search-results',
'defer-selected-search-results','plan-selected-search-results',
'search-selection-status','cmd-search-action-status','resume-search-batch',
'open-palette','cmd-results','cancel-search-selection','search-batch-estimate-review',
'search-batch-estimate-summary','search-batch-estimate-list',
'cancel-search-batch-estimates','confirm-search-batch-estimates','search-release-review',
'search-release-summary','search-release-milestone','search-release-due-date','search-release-list',
'cancel-search-release','confirm-search-release'
]) elements['#'+id]={{hidden:false,disabled:false,textContent:'',innerHTML:'',
addEventListener:(name,fn)=>listeners[id+':'+name]=fn,focus:()=>{{}}}};
const estimateInputs=[
{{dataset:{{searchBatchEstimate:'stackchain/dashboard#811'}},value:'25'}},
{{dataset:{{searchBatchEstimate:'stackchain/api#12'}},value:'30'}},
];
const document={{
querySelector:selector=>elements[selector] || null,
querySelectorAll:selector=>selector==='[data-search-batch-estimate]' ? estimateInputs : [],
}};
const calls=[];
const processorOptions=[];
const processor={{
run:(items,estimates)=>{{calls.push({{type:'run',items,estimates}});return Promise.resolve();}},
resume:()=>Promise.resolve(),pending:()=>0,
}};
const batchFactory=options=>{{processorOptions.push(options);return processor;}};
const planning={{capacity_minutes:90,estimates:{{'stackchain/existing#1':20}}}};
const todayWork={{limit:8,read:()=>[],planning:()=>planning,identity:item=>item.repository+'#'+item.number,
replacePlanning:value=>Object.assign(planning,value)}};
const todaySync={{enqueueConfiguration:()=>{{}},flush:()=>{{}}}};
const items=[
{{kind:'issue',state:'open',repository:'stackchain/dashboard',number:811,title:'Capacity'}},
{{kind:'issue',state:'open',repository:'stackchain/api',number:12,title:'API'}},
];
let selected=items;
const mounted=createSearchBatchPlan.mount(
document,batchFactory,todayWork,()=> 'timmy',()=>Promise.resolve(),()=>'',()=>Promise.resolve('queued'),
todaySync,item=>item,index=>selected[index],()=>{{}},value=>value,value=>value
);
mounted.plan.start();
items.forEach(item=>mounted.plan.toggle(item));
listeners['queue-selected-search-results:click']();
const before={{
calls:calls.slice(),
reviewHidden:elements['#search-batch-estimate-review'].hidden,
actionsHidden:elements['#search-batch-actions'].hidden,
markup:elements['#search-batch-estimate-list'].innerHTML,
budget:processorOptions[0].timeBudget(),
}};
listeners['confirm-search-batch-estimates:click']();
processorOptions[0].persistEstimate(items[0],25);
processorOptions[0].onProgress({{status:'complete',queued:['stackchain/dashboard#811','stackchain/api#12'],failed:[]}});
const afterCompleteHidden=elements['#search-batch-estimate-review'].hidden;
process.stdout.write(JSON.stringify({{before,calls,afterCompleteHidden}}));
"""
result = run_node(script)
assert result["before"]["calls"] == []
assert result["before"]["reviewHidden"] is False
assert result["before"]["actionsHidden"] is True
assert "Capacity" in result["before"]["markup"]
assert "data-search-batch-estimate" in result["before"]["markup"]
assert result["before"]["budget"] == {"capacity_minutes": 90, "planned_minutes": 20}
assert result["calls"] == [{
"type": "run",
"items": [
{"kind": "issue", "state": "open", "repository": "stackchain/dashboard", "number": 811, "title": "Capacity"},
{"kind": "issue", "state": "open", "repository": "stackchain/api", "number": 12, "title": "API"},
],
"estimates": {"stackchain/dashboard#811": 25, "stackchain/api#12": 30},
}]
assert result["afterCompleteHidden"] is True
def test_search_batch_reviews_and_applies_one_repository_release_plan_before_assignment():
script = f"""
const createSearchBatchPlan=require({json.dumps(str(SEARCH_BATCH_PLAN))});
const listeners={{}};
const elements={{}};
for (const id of [
'search-batch-actions','select-search-results','queue-selected-search-results',
'defer-selected-search-results','plan-selected-search-results','search-selection-status',
'cmd-search-action-status','resume-search-batch','open-palette','cmd-results',
'cancel-search-selection','search-batch-estimate-review','search-batch-estimate-summary',
'search-batch-estimate-list','cancel-search-batch-estimates','confirm-search-batch-estimates',
'search-release-review','search-release-summary','search-release-milestone',
'search-release-due-date','search-release-list','cancel-search-release','confirm-search-release'
]) elements['#'+id]={{hidden:false,disabled:false,textContent:'',innerHTML:'',value:'',
addEventListener:(name,fn)=>listeners[id+':'+name]=fn,focus:()=>{{}}}};
const document={{querySelector:selector=>elements[selector] || null,querySelectorAll:()=>[]}};
const calls=[];
const fetchJson=(url,options={{}})=>{{
calls.push({{url,method:options.method || 'GET',body:options.body ? JSON.parse(options.body) : null}});
if (url.endsWith('/milestones')) return Promise.resolve([{{id:9,title:'August RC'}},{{id:7,title:'Old',state:'closed'}}]);
const number=Number(url.split('/issues/')[1].split('/')[0]);
if (url.endsWith('/release-plan')) return Promise.resolve({{
number,milestone:{{id:9,title:'August RC'}},due_date:'2026-08-31T23:59:59Z'
}});
return Promise.resolve();
}};
const processorOptions=[];
const processors=[];
const batchFactory=options=>{{processorOptions.push(options);const processor={{
run:(items,estimates,context)=>{{calls.push({{run:items.map(item=>item.number),context}});return Promise.resolve();}},
resume:()=>Promise.resolve(),pending:()=>0,
}};processors.push(processor);return processor;}};
const planning={{capacity_minutes:null,estimates:{{}}}};
const todayWork={{limit:8,read:()=>[],planning:()=>planning,identity:item=>item.repository+'#'+item.number,replacePlanning:()=>{{}}}};
const items=[
{{kind:'issue',state:'open',repository:'stackchain/dashboard',number:815,title:'Release plan'}},
{{kind:'issue',state:'open',repository:'stackchain/dashboard',number:816,title:'Second issue'}},
];
const mounted=createSearchBatchPlan.mount(
document,batchFactory,todayWork,()=> 'timmy',fetchJson,()=>'',()=>Promise.resolve('queued'),
{{enqueueConfiguration:()=>{{}},flush:()=>{{}}}},item=>item,index=>items[index],()=>{{}},
value=>value,value=>value,null,null
);
mounted.plan.start();items.forEach(item=>mounted.plan.toggle(item));
listeners['plan-selected-search-results:click']().then(async()=>{{
const before={{calls:calls.slice(),reviewHidden:elements['#search-release-review'].hidden,
actionsHidden:elements['#search-batch-actions'].hidden,options:elements['#search-release-milestone'].innerHTML,
list:elements['#search-release-list'].innerHTML}};
elements['#search-release-milestone'].value='9';
elements['#search-release-milestone'].selectedIndex=0;
elements['#search-release-milestone'].options=[{{textContent:'August RC'}}];
elements['#search-release-due-date'].value='2026-08-31';
listeners['confirm-search-release:click']();
const queued=await processorOptions[2].queue({{...items[0],assigned_to_me:true}},
{{milestone_id:9,milestone_title:'August RC',due_date:'2026-08-31T23:59:59Z'}});
process.stdout.write(JSON.stringify({{before,calls,queued,journals:processorOptions.map(option=>option.journalName)}}));
}});
"""
result = run_node(script)
assert result["before"]["calls"] == [{
"url": "api/v1/repos/stackchain/dashboard/milestones", "method": "GET", "body": None,
}]
assert result["before"]["reviewHidden"] is False
assert result["before"]["actionsHidden"] is True
assert "August RC" in result["before"]["options"]
assert "Old" not in result["before"]["options"]
assert "Release plan" in result["before"]["list"]
assert result["calls"][1] == {
"run": [815, 816],
"context": {
"milestone_id": 9, "milestone_title": "August RC",
"due_date": "2026-08-31T23:59:59Z",
},
}
assert result["calls"][2:] == [{
"url": "api/v1/repos/stackchain/dashboard/issues/815/release-plan",
"method": "PATCH",
"body": {"milestone_id": 9, "due_date": "2026-08-31T23:59:59Z"},
}]
assert result["queued"] == "queued"
assert result["journals"] == [
"search-today-batch", "search-later-batch", "search-release-batch",
]
+10 -4
View File
@@ -247,7 +247,7 @@ def test_image_share_target_stages_one_supported_image_and_redirects_to_capture(
}
def test_image_share_target_rejects_multiple_images_without_staging_private_data():
def test_image_share_target_stages_ordered_evidence_bundle():
result = run_worker_scenario(
"""
const form = new FormData();
@@ -256,16 +256,19 @@ def test_image_share_target_rejects_multiple_images_without_staging_private_data
const request = new Request('https://forge.example/dashboard/', {method:'POST', body:form});
Object.defineProperty(request, 'mode', {value:'navigate'});
const response = await dispatch('fetch', request);
const record=state.sharedRecords['shared-image'];
process.stdout.write(JSON.stringify({
status:response.status, location:response.headers.get('Location'), records:Object.keys(state.sharedRecords),
status:response.status, location:response.headers.get('Location'),
names:record.attachments.map(value=>value.filename),sizes:record.attachments.map(value=>value.blob.size),
}));
"""
)
assert result == {
"status": 303,
"location": "/dashboard/?launch=new&shared=multiple",
"records": [],
"location": "/dashboard/?launch=new&shared=images",
"names": ["one.png", "two.jpg"],
"sizes": [3, 3],
}
@@ -787,6 +790,7 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
"/dashboard/static/security-center.js",
"/dashboard/static/markdown.js",
"/dashboard/static/commands.js",
"/dashboard/static/saved-searches.js",
"/dashboard/static/search-preview.js",
"/dashboard/static/search-defer.js",
"/dashboard/static/widgets.js",
@@ -833,6 +837,8 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
"/dashboard/static/search-batch-plan.js",
"/dashboard/static/conversation.js",
"/dashboard/static/comment-actions.js",
"/dashboard/static/issue-evidence-review.js",
"/dashboard/static/issue-evidence-editor.js",
"/dashboard/static/issue-attachment.js",
"/dashboard/static/issue-sheet.js",
"/dashboard/static/create-issue-sheet.js",
+17
View File
@@ -36,6 +36,23 @@ shared.consume({{
}
def test_shared_evidence_bundle_is_consumed_once_in_order():
script = f"""
const shared=require({json.dumps(str(MODULE))});const calls=[];
const store={{get:async()=>({{attachments:[
{{filename:'one.png',contentType:'image/png',blob:new Blob(['one'],{{type:'image/png'}})}},
{{filename:'two.jpg',contentType:'image/jpeg',blob:new Blob(['two'],{{type:'image/jpeg'}})}},
]}}),delete:async id=>calls.push(['delete',id])}};
(async()=>{{const result=await shared.consume({{marker:'images',store,restore:value=>calls.push(['restore',value.map(x=>x.filename)]),status:value=>calls.push(['status',value])}});process.stdout.write(JSON.stringify({{result,calls}}));}})();
"""
output = json.loads(subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True).stdout)
assert output == {"result": True, "calls": [
["restore", ["one.png", "two.jpg"]], ["delete", "shared-image"],
["status", "2 shared screenshots ready to file with this issue."],
]}
def test_invalid_shared_image_reports_error_without_touching_open_capture():
script = f"""
const shared = require({json.dumps(str(MODULE))});
+20
View File
@@ -85,6 +85,26 @@ process.stdout.write(JSON.stringify({{fullError,beforeReplace,oldest,replacement
assert output["restored"][0]["ownerLogin"] == "timmy"
def test_unfiled_capture_restores_ordered_evidence_bundle():
script = f"""
const createUnfiledCaptures=require({json.dumps(str(UNFILED))});
const values=new Map(),blobs=new Map();
const storage={{getItem:k=>values.get(k)||null,setItem:(k,v)=>values.set(k,v)}};
const attachmentStore={{put:async(id,value)=>blobs.set(id,value),get:async id=>blobs.get(id),delete:async id=>blobs.delete(id)}};
const image=name=>({{filename:name,contentType:'image/png',blob:new Blob([name],{{type:'image/png'}}),note:'Note '+name}});
(async()=>{{const captures=createUnfiledCaptures({{storage,attachmentStore,getCaptureLogin:()=>'timmy',getCurrentLogin:()=>'timmy',createId:()=>'bundle'}});
const saved=await captures.save({{title:'Journey',body:'Steps',attachments:['one','two','three'].map(image)}});
const resumed=await captures.resume(saved.id,'timmy');
process.stdout.write(JSON.stringify({{listed:captures.list()[0],names:resumed.attachments.map(x=>x.filename),notes:resumed.attachments.map(x=>x.note),stored:blobs.get('bundle').attachments.map(x=>x.note)}}));}})();
"""
output = run_node(script)
assert output["listed"]["attachmentCount"] == 3
assert output["names"] == ["one", "two", "three"]
assert output["notes"] == ["Note one", "Note two", "Note three"]
assert output["stored"] == output["notes"]
def test_replacing_oldest_capture_deletes_only_its_attachment_after_new_capture_is_durable():
script = f"""
const createUnfiledCaptures = require({json.dumps(str(UNFILED))});