Compare commits
49
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d97b2e84a | ||
|
|
502fcb30f5 | ||
|
|
b541c707fc | ||
|
|
b40a44fc45 | ||
|
|
d1adbe72d6 | ||
|
|
d6e6cf2e67 | ||
|
|
53706f18ab | ||
|
|
f0be3a44a6 | ||
|
|
b753cdd922 | ||
|
|
400534f446 | ||
|
|
a43ecac94b | ||
|
|
d6993c40fb | ||
|
|
966116e5ee | ||
|
|
d4ddac07ab | ||
|
|
b6684bb7ba | ||
|
|
07f5770aa8 | ||
|
|
f3876d359d | ||
|
|
e5b9833096 | ||
|
|
ae98564d9b | ||
|
|
b85fe4a0a3 | ||
|
|
a9becd079f | ||
|
|
99750d44f5 | ||
|
|
e4d0cc9115 | ||
|
|
77f22f3cd5 | ||
|
|
fde3ba21ca | ||
|
|
8cb92c6858 | ||
|
|
3e7a6c81fc | ||
|
|
084c0b5732 | ||
|
|
c73fbf8379 | ||
|
|
b47ed5d86e | ||
|
|
f0f415c65d | ||
|
|
2102b0e5da | ||
|
|
050390d6f6 | ||
|
|
be5603d41b | ||
|
|
4e074ae18e | ||
|
|
a4ae3e1c7f | ||
|
|
1a2297e943 | ||
|
|
611e79fc1e | ||
|
|
50817bed9a | ||
|
|
1f9f0f5c22 | ||
|
|
d776a2b003 | ||
|
|
7517d81046 | ||
|
|
091a01ba67 | ||
|
|
bad14d1b94 | ||
|
|
c4bb2f5eba | ||
|
|
d2a815c4bc | ||
|
|
3bc1d2f602 | ||
|
|
bd96c3caa3 | ||
|
|
f8ab6977ed |
No files matched your search
@@ -57,7 +57,7 @@ jobs:
|
||||
pip install -r requirements-e2e.txt
|
||||
python3 -m playwright install --with-deps chromium
|
||||
- name: Exercise packaged mobile work journeys
|
||||
run: python3 -m pytest tests/e2e/test_mobile_offline_issue_release.py tests/e2e/test_mobile_search_preview_navigation.py tests/e2e/test_mobile_search_week_plan.py tests/e2e/test_mobile_find_work_release.py tests/e2e/test_mobile_home_bootstrap_release.py tests/e2e/test_mobile_sign_out_release.py tests/e2e/test_mobile_today_handoff_release.py tests/e2e/test_mobile_today_wrap_up_release.py tests/e2e/test_mobile_today_summary_release.py tests/e2e/test_mobile_tomorrow_conflict_release.py tests/e2e/test_mobile_week_ahead_release.py tests/e2e/test_mobile_today_week_reschedule_release.py tests/e2e/test_mobile_wrap_up_handoff_release.py tests/e2e/test_mobile_following_release.py tests/e2e/test_mobile_detail_watch_release.py -q
|
||||
run: python3 -m pytest tests/e2e -q
|
||||
|
||||
release-candidate:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -19,6 +19,12 @@ threads, create and self-assign issues, discover, claim, and release issue assig
|
||||
list repository labels and open milestones, set or clear due dates on assigned issues, create issue comments, close assigned issues,
|
||||
inspect/comment on assigned pull
|
||||
requests, merge assigned pull requests, and submit pull-request reviews.
|
||||
After an exact merged commit fails release checks, its mobile release receipt can load the
|
||||
failed job evidence and prepare a draft rollback pull request. The server revalidates the
|
||||
operator's participation and push access, reverses only bounded UTF-8 files whose current
|
||||
default-branch content still matches the failed merge, and creates one atomic commit on a
|
||||
stable operator-owned branch. Conflicts, renames, binary files, and oversized changes fail
|
||||
closed; retrying converges on the same draft PR, which opens in the existing review workspace.
|
||||
Assigned-issue, assigned-pull-request, and unread-update conversation composers accept an ordered bundle of up to five PNG, JPEG, or WebP photos. Repeated camera captures append to the bundle, the gallery picker accepts multiple images, and each composer automatically optimizes oversized screenshots on-device to fit the 2 MB upload boundary. Before sending, the selected conversation photo can use the same touch editor as New issue evidence to crop, privacy-redact, highlight, or add an arrow; Apply replaces only that flattened derivative while preserving its caption and bundle position, and Cancel leaves the original unchanged.
|
||||
For online delivery, every photo uploads before the comment is posted to the exact conversation target, producing one ordered Markdown comment or reply; validation or upload failures keep the typed text and removable preview available for retry. Offline photo conversations admit every image Blob to IndexedDB before confirmation, keep only bounded metadata in localStorage, and checkpoint each upload separately so reconnect resumes at the first unconfirmed photo without duplicating an upload, comment, reply, or reply-and-read transition. 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
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
function createController({request, storage, login, createId = () => globalThis.crypto?.randomUUID?.() || String(Date.now())}) {
|
||||
const storageKey = 'stackchain.create-pull.v1.' + String(login || '').toLowerCase();
|
||||
let operationId = createId();
|
||||
let current = {
|
||||
repository:'', branches:[], head:'', base:'', expected_head_sha:'',
|
||||
title:'', body:'', draft:true,
|
||||
};
|
||||
try {
|
||||
const saved = JSON.parse(storage?.getItem?.(storageKey) || 'null');
|
||||
if (saved && typeof saved === 'object') {
|
||||
for (const field of ['repository', 'head', 'base', 'title', 'body']) {
|
||||
if (typeof saved[field] === 'string') current[field] = saved[field];
|
||||
}
|
||||
if (typeof saved.draft === 'boolean') current.draft = saved.draft;
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
function snapshot() {
|
||||
return JSON.parse(JSON.stringify(current));
|
||||
}
|
||||
|
||||
function persist() {
|
||||
storage?.setItem?.(storageKey, JSON.stringify({
|
||||
repository:current.repository, head:current.head, base:current.base,
|
||||
title:current.title, body:current.body, draft:current.draft,
|
||||
}));
|
||||
}
|
||||
|
||||
async function selectRepository(repository) {
|
||||
const options = await request('api/v1/repos/' + repository + '/pull-creation-options');
|
||||
const branches = Array.isArray(options?.branches) ? options.branches : [];
|
||||
const base = branches.some(branch => branch.name === options.default_branch) ? options.default_branch : (branches[0]?.name || '');
|
||||
const headBranch = branches.find(branch => branch.name !== base) || branches[0] || {};
|
||||
current = {
|
||||
...current, repository, branches, base,
|
||||
head:headBranch.name || '', expected_head_sha:headBranch.sha || '',
|
||||
};
|
||||
persist();
|
||||
return snapshot();
|
||||
}
|
||||
|
||||
function update(values) {
|
||||
current = {...current, ...values};
|
||||
if (Object.prototype.hasOwnProperty.call(values, 'head')) {
|
||||
current.expected_head_sha = current.branches.find(branch => branch.name === values.head)?.sha || '';
|
||||
}
|
||||
persist();
|
||||
return snapshot();
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
const result = await request('api/v1/repos/' + current.repository + '/pulls', {
|
||||
method:'POST',
|
||||
headers:{'Idempotency-Key':operationId},
|
||||
body:{
|
||||
head:current.head, base:current.base, title:current.title, body:current.body,
|
||||
draft:current.draft, expected_head_sha:current.expected_head_sha,
|
||||
},
|
||||
});
|
||||
operationId = createId();
|
||||
return result;
|
||||
}
|
||||
|
||||
return {
|
||||
state:snapshot,
|
||||
selectRepository,
|
||||
update,
|
||||
submit,
|
||||
};
|
||||
}
|
||||
|
||||
function createBinding({controller, render, status, onCreated}) {
|
||||
return {
|
||||
async repositoryChanged(repository) {
|
||||
status('Loading branches…');
|
||||
try {
|
||||
const state = await controller.selectRepository(repository);
|
||||
render(state);
|
||||
status(state.branches.length ? 'Choose the source and base branches.' : 'No branches are available.');
|
||||
return state;
|
||||
} catch (error) {
|
||||
status(error.message || 'Branches could not be loaded.');
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
changed(values) {
|
||||
const state = controller.update(values);
|
||||
render(state);
|
||||
return state;
|
||||
},
|
||||
async submit() {
|
||||
status('Creating pull request…');
|
||||
try {
|
||||
const result = await controller.submit();
|
||||
status(result.existing ? `Pull request #${result.number} is already open.` : `Pull request #${result.number} created.`);
|
||||
onCreated(result);
|
||||
return result;
|
||||
} catch (error) {
|
||||
status(error.message || 'The pull request could not be created. Your draft is safe.');
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function bindDashboard() {
|
||||
const qs = selector => document.querySelector(selector);
|
||||
const switchButton = qs('#switch-to-create-pull');
|
||||
switchButton.disabled = true;
|
||||
const identityResponse = await fetch('api/v1/background-identity').catch(()=>null);
|
||||
const identity = await identityResponse?.json().catch(()=>({}));
|
||||
if (!identityResponse?.ok || !identity?.login) {
|
||||
switchButton.title = 'Account identity is unavailable.';
|
||||
return null;
|
||||
}
|
||||
const login = identity.login;
|
||||
const root = qs('#create-pull-sheet');
|
||||
const repository = qs('#create-pull-repository');
|
||||
const head = qs('#create-pull-head');
|
||||
const base = qs('#create-pull-base');
|
||||
const title = qs('#create-pull-title');
|
||||
const body = qs('#create-pull-body');
|
||||
const submit = qs('#submit-create-pull');
|
||||
const request = async (url, options) => {
|
||||
const response = await fetch(url, options ? {
|
||||
method:options.method,
|
||||
headers:{'Content-Type':'application/json', ...options.headers},
|
||||
body:JSON.stringify(options.body),
|
||||
} : undefined);
|
||||
const payload = await response.json().catch(()=>({}));
|
||||
if (!response.ok) throw new Error(payload.error || payload.detail || 'Request failed.');
|
||||
return payload;
|
||||
};
|
||||
const controller = createController({request, storage:localStorage, login});
|
||||
const setOptions = (select, branches) => {
|
||||
select.replaceChildren(...branches.map(branch => {
|
||||
const option = document.createElement('option');
|
||||
option.value = option.textContent = branch.name;
|
||||
return option;
|
||||
}));
|
||||
};
|
||||
const render = state => {
|
||||
setOptions(head, state.branches);
|
||||
setOptions(base, state.branches);
|
||||
head.value = state.head;
|
||||
base.value = state.base;
|
||||
head.disabled = base.disabled = !state.branches.length;
|
||||
qs('#create-pull-head-receipt').textContent = state.expected_head_sha ? 'Source at ' + state.expected_head_sha.slice(0, 12) : '';
|
||||
submit.disabled = !(state.repository && state.head && state.base && state.head !== state.base && title.value.trim());
|
||||
};
|
||||
const binding = createBinding({
|
||||
controller, render,
|
||||
status:message=>{ qs('#create-pull-status').textContent = message; },
|
||||
onCreated:result=>{
|
||||
root.hidden = true;
|
||||
qs('main').inert = false;
|
||||
location.hash = '#/my-work/pull/' + result.repository + '/' + result.number;
|
||||
location.reload();
|
||||
},
|
||||
});
|
||||
const update = () => binding.changed({
|
||||
head:head.value, base:base.value, title:title.value, body:body.value,
|
||||
draft:document.querySelector('input[name="create-pull-mode"]:checked')?.value !== 'ready',
|
||||
});
|
||||
repository.addEventListener('change', () => binding.repositoryChanged(repository.value).catch(()=>{}));
|
||||
[head,base,title,body].forEach(field => field.addEventListener('input', update));
|
||||
document.querySelectorAll('input[name="create-pull-mode"]').forEach(field => field.addEventListener('change', () => {
|
||||
update();
|
||||
submit.textContent = field.value === 'ready' && field.checked ? 'Create ready pull request' : 'Create draft pull request';
|
||||
}));
|
||||
qs('#create-pull-form').addEventListener('submit', event => {
|
||||
event.preventDefault();
|
||||
update();
|
||||
binding.submit().catch(()=>{});
|
||||
});
|
||||
const close = () => {
|
||||
root.hidden = true;
|
||||
qs('main').inert = false;
|
||||
qs('#new-issue').focus();
|
||||
};
|
||||
qs('#cancel-create-pull').addEventListener('click', close);
|
||||
switchButton.addEventListener('click', () => {
|
||||
qs('#cancel-new-issue').click();
|
||||
repository.replaceChildren(...Array.from(qs('#create-issue-repository').options).map(source => {
|
||||
const option = document.createElement('option');
|
||||
option.value = source.value;
|
||||
option.textContent = source.textContent;
|
||||
return option;
|
||||
}));
|
||||
root.hidden = false;
|
||||
qs('main').inert = true;
|
||||
qs('#cancel-create-pull').focus();
|
||||
});
|
||||
root.addEventListener('keydown', event => {
|
||||
if (event.key === 'Escape') { event.preventDefault(); close(); }
|
||||
});
|
||||
switchButton.disabled = false;
|
||||
return binding;
|
||||
}
|
||||
|
||||
const cp = {createController, createBinding, b:bindDashboard};
|
||||
if (typeof module !== 'undefined') module.exports = cp;
|
||||
else cp.b();
|
||||
+81
-3
@@ -35,7 +35,20 @@ header { position: sticky; top: 0; z-index: 20; padding: 12px 16px; display:flex
|
||||
.release-watchlist-item { display:grid; grid-template-columns:minmax(0,1fr) auto; align-items:center; gap:10px; padding:10px; border:1px solid #334155; border-radius:10px; }
|
||||
.release-watchlist-item > div { display:grid; min-width:0; gap:3px; overflow-wrap:anywhere; }
|
||||
.release-watchlist-item > button { width:auto; min-width:88px; }
|
||||
@media (max-width:359px) { .release-receipt-actions { grid-template-columns:1fr; } }
|
||||
.release-watchlist-actions { display:grid; grid-template-columns:1fr 1fr; gap:8px; min-width:min(240px,46vw); }
|
||||
.release-watchlist-actions > button { min-height:44px; width:100%; }
|
||||
.release-branch-cleanup-status { color:#cbd5e1; }
|
||||
.release-failure-summary { display:grid; gap:8px; min-width:0; margin-top:8px; padding-top:8px; border-top:1px solid #334155; overflow-x:hidden; }
|
||||
.release-failure-summary > button { min-height:44px; }
|
||||
.release-failure-recovery { display:grid; gap:8px; min-width:0; padding:10px; border:1px solid #7f1d1d; border-radius:8px; background:#180f17; overflow-x:hidden; }
|
||||
.release-failure-recovery pre { box-sizing:border-box; max-width:100%; max-height:32dvh; margin:0; padding:10px; overflow:auto; white-space:pre-wrap; overflow-wrap:anywhere; background:#07101d; }
|
||||
.release-failure-actions { display:grid; grid-template-columns:1fr 1fr; gap:8px; min-width:0; }
|
||||
.release-failure-actions > button, .release-failure-actions > a { min-height:44px; width:100%; }
|
||||
@media (max-width:359px) {
|
||||
.release-receipt-actions, .release-watchlist-actions, .release-failure-actions { grid-template-columns:1fr; }
|
||||
.release-watchlist-item { grid-template-columns:1fr; }
|
||||
.release-watchlist-actions { min-width:0; width:100%; }
|
||||
}
|
||||
.issue-filing-receipt-panel { box-sizing:border-box; width:min(560px,100%); max-height:100dvh; overflow:auto; overflow-x:hidden; padding:18px; padding-bottom:calc(18px + env(safe-area-inset-bottom)); border:1px solid #4ade80; border-radius:18px 18px 0 0; background:#0b1526; overflow-wrap:anywhere; }
|
||||
.issue-filing-receipt-panel h2, .issue-filing-receipt-panel h3 { margin:.25rem 0; }
|
||||
.issue-filing-receipt-actions { display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-top:16px; }
|
||||
@@ -792,6 +805,17 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.ci-check-copy { min-width:0; display:grid; gap:3px; overflow-wrap:anywhere; }
|
||||
.ci-check-copy strong, .ci-check-copy span { min-width:0; overflow-wrap:anywhere; }
|
||||
.ci-check-link { min-height:44px; display:flex; align-items:center; justify-content:center; padding:0 10px; border:1px solid #60a5fa; border-radius:8px; white-space:nowrap; }
|
||||
.ci-check-actions { display:flex; flex-wrap:wrap; align-items:center; justify-content:flex-end; gap:6px; min-height:44px; }
|
||||
.ci-check-inspect { min-height:44px; white-space:nowrap; }
|
||||
.ci-check-recovery { max-width:100%; min-width:0; margin:0 8px 8px; padding:10px; border:1px solid #dc2626; border-radius:8px; background:#101b2e; }
|
||||
.ci-check-recovery[hidden] { display:none; }
|
||||
.ci-check-recovery h3 { margin:0 0 6px; overflow-wrap:anywhere; }
|
||||
.ci-check-log { max-width:100%; max-height:42vh; margin:8px 0; padding:10px; overflow-x:auto; overflow-y:auto; border:1px solid #2a496e; border-radius:6px; background:#07101d; color:#dbeafe; font-size:.78rem; white-space:pre; }
|
||||
.ci-check-recovery-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; padding-top:6px; background:#101b2e; }
|
||||
.ci-check-recovery-actions button { min-height:44px; }
|
||||
.pull-branch-update { max-width:100%; min-width:0; margin:10px 0; padding:12px; border:1px solid #60a5fa; border-radius:10px; overflow-wrap:anywhere; }
|
||||
.pull-branch-update h3 { margin:0 0 6px; }
|
||||
.pull-branch-update button { width:100%; min-height:44px; }
|
||||
.update-sheet { position:fixed; inset:0; z-index:55; display:none; justify-content:flex-end; background:rgba(5,12,21,.72); backdrop-filter:blur(4px); }
|
||||
.update-sheet.open { display:flex; }
|
||||
.update-sheet-panel { width:min(560px,100%); height:100%; overflow:auto; padding:18px; background:#0b1526; border-left:1px solid #2a496e; }
|
||||
@@ -958,8 +982,13 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.issue-sheet-actions #watch-issue-detail, .pull-sheet-actions #watch-pull-detail { min-width:0; min-height:44px; }
|
||||
.detail-watch-status:not(:empty) { margin-top:8px; overflow-wrap:anywhere; }
|
||||
.issue-sheet-actions a { border:1px solid #60a5fa; border-radius:10px; font-weight:700; }
|
||||
.issue-handoff, .pull-ownership, .pull-review-request { margin-top:14px; padding:12px; border:1px solid #2a496e; border-radius:12px; }
|
||||
.issue-handoff > div, .pull-ownership > div, .pull-review-request > div { display:grid; gap:8px; margin-top:10px; }
|
||||
.issue-handoff, .pull-ownership, .pull-review-request, .pull-lifecycle { margin-top:14px; padding:12px; border:1px solid #2a496e; border-radius:12px; }
|
||||
.issue-handoff > div, .pull-ownership > div, .pull-review-request > div, .pull-lifecycle > div { display:grid; gap:8px; margin-top:10px; }
|
||||
.pull-lifecycle { border-color:#b45353; }
|
||||
.pull-lifecycle button { min-height:44px; border-color:#ef4444; background:#5f1d24; color:#fff; }
|
||||
.pull-close-receipt { margin-top:14px; padding:12px; border:1px solid #4ade80; border-radius:12px; background:#10291e; }
|
||||
.pull-close-receipt h3 { margin-top:0; }
|
||||
.pull-close-receipt button { width:100%; min-height:44px; border-color:#4ade80; }
|
||||
.issue-handoff select, .pull-ownership select, .pull-review-request select { width:100%; max-width:100%; padding:8px; border:1px solid #1f3a5f; border-radius:8px; background:#0b1526; color:var(--text); }
|
||||
.issue-handoff select, .issue-handoff button { min-height:44px; }
|
||||
.pull-ownership select, .pull-ownership button { min-height:44px; }
|
||||
@@ -1259,6 +1288,42 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
.pull-diff-empty { margin:8px 0; padding:10px; border:1px dashed #4e6b8a; border-radius:8px; }
|
||||
.pull-review-tools { display:flex; align-items:center; justify-content:space-between; gap:8px; margin:8px 0; }
|
||||
.pull-review-tools button { min-height:44px; }
|
||||
.pull-reviewer-summary { margin:10px 0; padding:10px; border:1px solid #203a5c; border-radius:10px; }
|
||||
.pull-reviewer-summary h3 { margin:0 0 6px; font-size:14px; }
|
||||
.pull-reviewer-status { padding:8px 0; border-top:1px solid #203a5c; overflow-wrap:anywhere; }
|
||||
.pull-reviewer-status:first-child { border-top:0; }
|
||||
.pull-reviewer-status-heading { display:flex; justify-content:space-between; gap:10px; }
|
||||
.pull-reviewer-status-heading span { text-align:right; }
|
||||
.cancel-review-request { min-height:44px; width:100%; margin-top:8px; }
|
||||
.pull-review-feedback { margin-top:8px; border:1px solid #2a496e; border-radius:8px; padding:0 8px 8px; }
|
||||
.pull-review-feedback > summary { min-height:44px; display:flex; align-items:center; cursor:pointer; }
|
||||
.pull-review-feedback-summary { margin:4px 0 10px; white-space:pre-wrap; }
|
||||
.pull-review-feedback-file { margin-top:8px; padding-top:8px; border-top:1px solid #203a5c; }
|
||||
.pull-review-feedback-file h4 { margin:0 0 4px; overflow-wrap:anywhere; }
|
||||
.pull-review-feedback-file ul { margin:0; padding-left:20px; }
|
||||
.pull-review-feedback-file li { margin:6px 0; }
|
||||
.pull-review-feedback-file small { display:block; color:#93c5fd; }
|
||||
.pull-review-feedback-file button { min-height:44px; width:100%; margin-top:4px; }
|
||||
.address-review-feedback, [data-load-review-feedback] { min-height:44px; width:100%; margin-top:8px; }
|
||||
.pull-feedback-pass { margin-top:10px; padding:10px; border:1px solid #3b82f6; border-radius:10px; overflow-wrap:anywhere; }
|
||||
.pull-feedback-pass-heading { display:flex; align-items:start; justify-content:space-between; gap:8px; }
|
||||
.pull-feedback-pass-heading h4 { margin:2px 0 8px; }
|
||||
.pull-feedback-pass p { white-space:pre-wrap; }
|
||||
.pull-feedback-pass textarea { width:100%; min-height:88px; box-sizing:border-box; }
|
||||
#make-pull-feedback-fix { width:100%; margin-top:8px; border-color:#4ade80; }
|
||||
.pull-feedback-file-editor { display:grid; min-width:0; gap:8px; margin-top:10px; padding:10px; border:1px solid #4ade80; border-radius:10px; overflow-x:hidden; }
|
||||
.pull-feedback-file-editor[hidden] { display:none; }
|
||||
.pull-feedback-file-editor h5 { margin:0; overflow-wrap:anywhere; }
|
||||
#pull-feedback-file-content { min-height:36dvh; resize:vertical; font:13px/1.45 ui-monospace, SFMono-Regular, Consolas, monospace; tab-size:2; white-space:pre; overflow:auto; }
|
||||
#pull-feedback-commit-message { box-sizing:border-box; width:100%; min-width:0; }
|
||||
.pull-feedback-file-actions { display:grid; grid-template-columns:1fr 1fr; gap:8px; min-width:0; }
|
||||
@media (max-width:359px) { .pull-feedback-file-actions { grid-template-columns:1fr; } }
|
||||
.pull-feedback-dispositions { display:grid; grid-template-columns:1fr; gap:6px; margin:10px 0; padding:8px; }
|
||||
.pull-feedback-dispositions button[aria-pressed="true"] { border-color:#60a5fa; background:#173b63; }
|
||||
.pull-feedback-navigation { display:grid; grid-template-columns:1fr 1fr; gap:8px; margin-top:8px; }
|
||||
.pull-feedback-pass button { min-height:44px; }
|
||||
#finish-pull-feedback, #request-feedback-review { width:100%; margin-top:8px; }
|
||||
#request-updated-pull-review { min-height:44px; width:100%; margin-top:8px; }
|
||||
.pull-review { margin-top:14px; overflow:hidden; border:1px solid #2a496e; border-radius:10px; padding:0 10px 10px; }
|
||||
.pull-review summary { min-height:44px; display:flex; align-items:center; cursor:pointer; }
|
||||
.pull-review summary h2 { margin:0; font-size:16px; }
|
||||
@@ -1495,3 +1560,16 @@ textarea { resize: vertical; min-height: 120px; }
|
||||
transition: transform 120ms ease, border-color 120ms ease;
|
||||
}
|
||||
}
|
||||
|
||||
.create-pull-sheet{position:fixed;inset:0;z-index:75;background:rgba(3,7,18,.72);display:grid;place-items:end center;padding:16px}
|
||||
.create-pull-sheet[hidden]{display:none}
|
||||
.create-pull-panel{width:min(100%,680px);max-height:calc(100dvh - 32px);overflow:auto;background:var(--panel);border:1px solid var(--border);border-radius:20px;padding:20px;padding-bottom:max(20px,env(safe-area-inset-bottom))}
|
||||
.create-pull-header{display:flex;align-items:center;justify-content:space-between;gap:12px}
|
||||
.create-pull-header h3{margin:2px 0 0}
|
||||
.create-pull-panel form,.create-pull-panel label{display:grid;gap:6px}
|
||||
.create-pull-panel form{gap:14px}
|
||||
.create-pull-branches{display:grid;grid-template-columns:1fr 1fr;gap:12px}
|
||||
.create-pull-mode{display:flex;gap:18px;border:1px solid var(--border);border-radius:12px;padding:10px 12px}
|
||||
.create-pull-mode label{display:flex;align-items:center;gap:7px}
|
||||
.create-pull-panel button,.create-pull-panel select,.create-pull-panel input{min-height:44px}
|
||||
@media(max-width:600px){.create-pull-sheet{padding:0}.create-pull-panel{width:100%;max-height:100dvh;border-radius:18px 18px 0 0}.create-pull-branches{grid-template-columns:1fr}}
|
||||
+43
-30
@@ -328,7 +328,7 @@
|
||||
let launchFilterResolved = false;
|
||||
try {
|
||||
const savedFilter = sessionStorage.getItem(WORK_FILTER_KEY);
|
||||
if (['all', 'today', 'agenda', 'attention', 'filed', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)) {
|
||||
if (['all', 'today', 'agenda', 'attention', 'filed', 'authored', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)) {
|
||||
selectedWorkFilter = savedFilter;
|
||||
savedWorkFilter = savedFilter;
|
||||
launchFilterResolved = true;
|
||||
@@ -368,6 +368,7 @@
|
||||
let selectedPullDetail = null;
|
||||
let pullConversation = null;
|
||||
let pullReviewState = null;
|
||||
|
||||
let creatingIssue = false;
|
||||
let createAndStartRequested = false;
|
||||
let pendingIssueFilingIntent = 'create-and-assign';
|
||||
@@ -386,23 +387,24 @@
|
||||
let confirmedOwnerLogin = '';
|
||||
let planningOwnerLogin = '';
|
||||
let activeFlushLogin = '';
|
||||
let releaseReceipt = null;
|
||||
function attachReleaseReceipt() {
|
||||
if (releaseReceipt) return releaseReceipt;
|
||||
releaseReceipt = createReleaseReceipt({
|
||||
let rR = null;
|
||||
function rRC() {
|
||||
if (rR) return rR;
|
||||
rR = createReleaseReceipt({
|
||||
storage:localStorage, getLogin:()=>confirmedOwnerLogin, fetchJson:fetchReviewJson,
|
||||
launcher:qs('#release-receipt-launcher'), dialog:qs('#release-receipt-sheet'),
|
||||
statusNode:qs('#release-receipt-status'), checksNode:qs('#release-receipt-checks'),
|
||||
releaseNode:qs('#release-receipt-link'),
|
||||
listNode:qs('#release-watchlist'),
|
||||
openPull:openPullSheet,
|
||||
});
|
||||
releaseReceipt.bind();
|
||||
rR.bind();
|
||||
qs('#close-release-receipt').addEventListener('click', () => qs('#release-receipt-sheet').close());
|
||||
qs('#refresh-release-receipt').addEventListener('click', () => releaseReceipt.refresh().catch(error => {
|
||||
qs('#refresh-release-receipt').addEventListener('click', () => rR.refresh().catch(error => {
|
||||
qs('#release-receipt-status').textContent = error.message + ' Retry when connected.';
|
||||
}));
|
||||
qs('#dismiss-release-receipt').addEventListener('click', () => releaseReceipt.dismiss());
|
||||
return releaseReceipt;
|
||||
qs('#dismiss-release-receipt').addEventListener('click', () => rR.dismiss());
|
||||
return rR;
|
||||
}
|
||||
const completedFiledReview = createCompletedFiledReview({
|
||||
storage: localStorage,
|
||||
@@ -1279,7 +1281,7 @@
|
||||
trigger, status: qs('#my-work-action-status'), retryLabel:'Tap the work card to retry.',
|
||||
}, () => {
|
||||
if (!pullController) {
|
||||
pullController = createPullSheet({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
pullController = createPullSheet({ fetchJson: fetchReviewJson, storage: localStorage, onState:refreshMyWorkView });
|
||||
createPullSheet.bindOwnershipControls(document, pullController, () => selectedPull, async item => {
|
||||
const continuing = workSession.checkpointed(item);
|
||||
lastContextSnapshot = createPullSheet.removeFromSnapshot(lastContextSnapshot, item);
|
||||
@@ -1289,7 +1291,7 @@
|
||||
return false;
|
||||
}, ()=>selectedPullDetail, ()=>confirmedOwnerLogin);
|
||||
}
|
||||
attachReleaseReceipt();
|
||||
rRC();
|
||||
if (!reviewController) reviewController = createReviewController({ fetchJson: fetchReviewJson, storage: localStorage });
|
||||
if (!wrapPreference) {
|
||||
wrapPreference = createReviewController.createWrapPreference({
|
||||
@@ -1305,7 +1307,7 @@
|
||||
try {
|
||||
if (!localStorage.getItem('stackchain.release-receipt.v1:' + account)) return;
|
||||
} catch (_error) { return; }
|
||||
ensurePullWorkflow().then(() => releaseReceipt.restore()).catch(() => {});
|
||||
ensurePullWorkflow().then(() => rR.restore()).catch(() => {});
|
||||
}
|
||||
const draftInbox = createDraftInbox({ storage: localStorage, getCurrentLogin: () => activeFlushLogin });
|
||||
outboxCoordinator.subscribe(() => refreshMyWorkView());
|
||||
@@ -3497,10 +3499,10 @@
|
||||
if (selectedWorkFilter === 'agenda') return ['issue'];
|
||||
if (selectedWorkFilter === 'attention') return ['issue', 'pull', 'review'];
|
||||
if (selectedWorkFilter === 'filed') return ['filed'];
|
||||
if (selectedWorkFilter === 'issue') return ['issue'];
|
||||
if (selectedWorkFilter === 'pull') return ['pull'];
|
||||
if (selectedWorkFilter === 'review') return ['review'];
|
||||
if (selectedWorkFilter === 'all') return ['issue', 'filed', 'pull', 'review'];
|
||||
if (['issue', 'pull', 'review', 'authored'].includes(selectedWorkFilter)) {
|
||||
return [selectedWorkFilter];
|
||||
}
|
||||
if (selectedWorkFilter === 'all') return ['issue', 'filed', 'pull', 'review', 'authored'];
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -3746,7 +3748,7 @@
|
||||
}
|
||||
|
||||
function updateWorkPaginationControls() {
|
||||
const labels = { issue: 'issues', filed: 'filed issues', pull: 'pull requests', review: 'review requests' };
|
||||
const labels = { issue: 'issues', filed: 'filed issues', pull: 'pull requests', review: 'review requests', authored: 'pull requests' };
|
||||
const streams = activeWorkStreams();
|
||||
const incomplete = streams.filter(stream => workPagination[stream]?.has_more);
|
||||
const summaries = streams.flatMap(stream => {
|
||||
@@ -4536,7 +4538,7 @@
|
||||
qs('#pull-review-progress').textContent = pullReviewState.total ?
|
||||
pullReviewState.reviewed.length + ' of ' + pullReviewState.total + ' files reviewed' : 'No changed files to review';
|
||||
qs('#next-unreviewed-pull-file').disabled = pullReviewState.complete;
|
||||
const eligibility = createPullSheet.mergeEligibility(detail, pullReviewState);
|
||||
const eligibility = createPullSheet.review(detail, pullReviewState, document);
|
||||
qs('#pull-merge-state').textContent = eligibility.reason;
|
||||
qs('#merge-pull').disabled = !eligibility.allowed;
|
||||
qs('#pull-files').innerHTML = (detail.files || []).length ? detail.files.map((file, index) =>
|
||||
@@ -4573,9 +4575,7 @@
|
||||
return;
|
||||
}
|
||||
selectedPullDetail = { ...selectedPullDetail, ...status };
|
||||
const eligibility = createPullSheet.mergeEligibility(selectedPullDetail, pullReviewState);
|
||||
qs('#pull-merge-state').textContent = eligibility.reason;
|
||||
qs('#merge-pull').disabled = !eligibility.allowed;
|
||||
renderPullReview(selectedPullDetail);
|
||||
qs('#pull-review-status').textContent = 'Checks refreshed for the current head.';
|
||||
}
|
||||
|
||||
@@ -4606,6 +4606,7 @@
|
||||
async function openPullSheet(item, trigger, offlineDetail = null) {
|
||||
if (!item) return;
|
||||
if (!await ensurePullWorkflow(trigger)) return;
|
||||
|
||||
pullDetailPosition.open(workDetailIdentity('pull', item));
|
||||
qs('#pull-review').inert = false;
|
||||
qs('#pull-ownership').inert = false;
|
||||
@@ -4648,6 +4649,7 @@
|
||||
qs('#pull-checks-summary').textContent = 'Not loaded';
|
||||
qs('#pull-check-list').textContent = '';
|
||||
qs('#pull-checks').open = false;
|
||||
|
||||
qs('#pull-merge-state').textContent = 'Review data not loaded';
|
||||
qs('#merge-pull').disabled = true;
|
||||
qs('#merge-pull').textContent = workSession.active() ? 'Merge & next' : 'Merge';
|
||||
@@ -5745,11 +5747,7 @@
|
||||
planButton.hidden = !searchWeekPlan.eligible(detail);
|
||||
planButton.textContent = detail.assigned_to_me ? 'Plan ahead' : 'Assign & plan ahead';
|
||||
planButton.disabled = searchWeekPlan.pending();
|
||||
startButton.hidden = !(detail.reviewable || (detail.kind === 'issue' &&
|
||||
(detail.reopenable || (detail.state === 'open' && (detail.claimable || detail.assigned_to_me)))));
|
||||
startButton.textContent = detail.reviewable ? 'Review now' : detail.reopenable ? 'Reopen & resume' :
|
||||
(detail.assigned_to_me ? 'Start in Today' : 'Assign & start');
|
||||
startButton.disabled = state.status === 'claiming' || state.status === 'reopening';
|
||||
renderSearchPreviewStart(detail, state, startButton);
|
||||
renderSearchPreviewWatch(detail, state, watchButton);
|
||||
followingQueue.preview(state);
|
||||
const shareStatus = {
|
||||
@@ -5771,9 +5769,7 @@
|
||||
fetchJson:searchSubscription.preview,
|
||||
fetchConversation:(item,page)=>fetchReviewJson(searchPreviewConversationPath(item,page)),
|
||||
fetchReview:searchSubscription.review,
|
||||
mutate:(detail,action)=>fetchReviewJson(
|
||||
searchPreviewPath(detail).replace(/\?.*$/, '') + '/' + action, {method:'PATCH'}
|
||||
),
|
||||
mutate:searchPreviewMutation(fetchReviewJson),
|
||||
watch:(detail,watching) => searchSubscription.watch(detail, watching).then(result =>
|
||||
followingQueue.load().catch(() => {}).then(() => result)),
|
||||
...searchPreviewReplyOptions(fetchReviewJson, localStorage, globalThis.crypto),
|
||||
@@ -5867,6 +5863,14 @@
|
||||
}
|
||||
const searchAssignAndStart = createSearchStart(detail => searchPreview.claim(detail));
|
||||
const searchReopenAndStart = createSearchStart(detail => searchPreview.reopen(detail));
|
||||
const recoverSearchPull = createSearchAuthoredPullRecovery({
|
||||
confirm,
|
||||
reopen:detail => searchPreview.reopenPull(detail),
|
||||
refresh:load,
|
||||
find:detail => lastMyWork.find(item => item.key === detail.repository + '#' + detail.number),
|
||||
open:item => openRoutedWork(item, qs('#start-search-result')),
|
||||
unavailable:message => qs('#search-preview-status').textContent = message,
|
||||
});
|
||||
const mobileSearchViewport = createMobileSearchViewport({
|
||||
palette: qs('#cmd-palette'),
|
||||
results: qs('#cmd-results'),
|
||||
@@ -6215,6 +6219,14 @@
|
||||
});
|
||||
qs('#start-search-result').addEventListener('click', async () => {
|
||||
const detail = searchPreviewDetail;
|
||||
if (detail?.authored_pull_reopenable) {
|
||||
try {
|
||||
await recoverSearchPull(detail);
|
||||
} catch (error) {
|
||||
qs('#search-preview-status').textContent = error.message + ' Retry.';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (detail?.reviewable) {
|
||||
taskOverlayHistory.leave();
|
||||
detail.kind = 'review';
|
||||
@@ -7245,6 +7257,7 @@
|
||||
if (event.currentTarget.open) loadPullReview();
|
||||
});
|
||||
qs('#pull-review-retry').addEventListener('click', loadPullReview);
|
||||
|
||||
qs('#refresh-pull-checks').addEventListener('click', async () => {
|
||||
if (!selectedPull || !selectedPullDetail?.head_sha) return;
|
||||
const item = selectedPull;
|
||||
@@ -7356,7 +7369,7 @@
|
||||
qs('#pull-sheet-status').textContent = 'Merging pull request…';
|
||||
try {
|
||||
const mergeResult = await pullController.merge(selectedPull, selectedPullDetail.head_sha);
|
||||
releaseReceipt.capture(merging, mergeResult);
|
||||
rR.capture(merging, mergeResult);
|
||||
closePullSheet();
|
||||
lastMyWork = lastMyWork.filter(item =>
|
||||
!(item.kind === 'pull' && item.repository === merging.repository && item.number === merging.number)
|
||||
|
||||
@@ -197,6 +197,7 @@
|
||||
<button class="work-filter" data-work-filter="agenda" aria-pressed="false">Agenda <span data-work-count="agenda">0</span></button>
|
||||
<button class="work-filter" data-work-filter="attention" aria-pressed="false">Attention <span data-work-count="attention">0</span></button>
|
||||
<button class="work-filter" data-work-filter="filed" aria-pressed="false">Filed <span data-work-count="filed">0</span></button>
|
||||
<button class="work-filter" data-work-filter="authored" aria-pressed="false">My PRs <span data-work-count="authored">0</span></button>
|
||||
<button class="work-filter" data-work-filter="issue" aria-pressed="false">Issues <span data-work-count="issue">0</span></button>
|
||||
<button class="work-filter" data-work-filter="pull" aria-pressed="false">PRs <span data-work-count="pull">0</span></button>
|
||||
<button class="work-filter" data-work-filter="review" aria-pressed="false">Reviews <span data-work-count="review">0</span></button>
|
||||
@@ -1280,6 +1281,7 @@
|
||||
<section class="create-issue-panel">
|
||||
<div class="create-issue-header">
|
||||
<h3 id="create-issue-heading">Capture work</h3>
|
||||
<button id="switch-to-create-pull" type="button">Pull request</button>
|
||||
<button id="cancel-new-issue" type="button">Cancel</button>
|
||||
</div>
|
||||
<aside class="today-capture-interruption" id="today-capture-interruption" role="status" hidden>
|
||||
@@ -1721,10 +1723,66 @@
|
||||
<div id="pull-review-status" class="small" aria-live="polite">Expand to load changed files and merge readiness.</div>
|
||||
<button class="pull-retry" id="pull-review-retry" type="button" hidden>Retry review data</button>
|
||||
<div class="row"><span class="pill" id="pull-ci-state">CI unknown</span><span class="pill" id="pull-merge-state">Review data not loaded</span></div>
|
||||
<section class="pull-branch-update" id="pull-branch-update" aria-labelledby="pull-branch-update-heading" hidden>
|
||||
<h3 id="pull-branch-update-heading">Bring branch up to date</h3>
|
||||
<p class="small" id="pull-branch-update-status" role="status" aria-live="assertive"></p>
|
||||
<button id="update-pull-branch" type="button">Update branch</button>
|
||||
</section>
|
||||
<section class="pull-reviewer-summary" aria-labelledby="pull-reviewer-heading">
|
||||
<h3 id="pull-reviewer-heading">Reviewer status</h3>
|
||||
<div id="pull-reviewer-status" class="small" aria-live="polite">Reviewer status not loaded.</div>
|
||||
<div id="pull-reviewer-statuses"></div>
|
||||
<button id="request-updated-pull-review" type="button" hidden>Request updated review</button>
|
||||
<section class="pull-feedback-pass" id="pull-feedback-pass" aria-labelledby="pull-feedback-heading" hidden>
|
||||
<div class="pull-feedback-pass-heading">
|
||||
<div><span class="small" id="pull-feedback-progress"></span><h4 id="pull-feedback-heading">Address review feedback</h4></div>
|
||||
<button id="close-pull-feedback" type="button">Close</button>
|
||||
</div>
|
||||
<p class="small" id="pull-feedback-location"></p>
|
||||
<p id="pull-feedback-body"></p>
|
||||
<div class="small" id="pull-feedback-context" aria-live="polite"></div>
|
||||
<button id="make-pull-feedback-fix" type="button" hidden>Make code change</button>
|
||||
<section class="pull-feedback-file-editor" id="pull-feedback-file-editor" hidden>
|
||||
<h5>Edit <span id="pull-feedback-file-path"></span></h5>
|
||||
<label for="pull-feedback-file-content">File content</label>
|
||||
<textarea id="pull-feedback-file-content" spellcheck="false" maxlength="131072"></textarea>
|
||||
<label for="pull-feedback-commit-message">Commit message</label>
|
||||
<input id="pull-feedback-commit-message" maxlength="120" placeholder="fix: address review feedback">
|
||||
<div class="pull-feedback-file-actions">
|
||||
<button id="cancel-pull-feedback-fix" type="button" hidden>Cancel change</button>
|
||||
<button id="commit-pull-feedback-fix" type="button" hidden>Commit to pull branch</button>
|
||||
</div>
|
||||
</section>
|
||||
<fieldset class="pull-feedback-dispositions">
|
||||
<legend>Disposition</legend>
|
||||
<button type="button" data-feedback-disposition="addressed">Addressed</button>
|
||||
<button type="button" data-feedback-disposition="discussion">Needs discussion</button>
|
||||
<button type="button" data-feedback-disposition="skipped">Skip for now</button>
|
||||
</fieldset>
|
||||
<label for="pull-feedback-note">Response note (optional)</label>
|
||||
<textarea id="pull-feedback-note" maxlength="1000" placeholder="What changed or needs discussion?"></textarea>
|
||||
<div class="pull-feedback-navigation">
|
||||
<button id="previous-pull-feedback" type="button">Previous</button>
|
||||
<button id="next-pull-feedback" type="button">Next</button>
|
||||
</div>
|
||||
<button id="finish-pull-feedback" type="button" disabled>Post feedback response</button>
|
||||
<button id="request-feedback-review" type="button" hidden>Request updated review from this reviewer</button>
|
||||
<div id="pull-feedback-status" class="small" role="status" aria-live="assertive"></div>
|
||||
</section>
|
||||
</section>
|
||||
<details class="ci-checks" id="pull-checks">
|
||||
<summary><span>Checks</span><span class="small" id="pull-checks-summary">Not loaded</span></summary>
|
||||
<button class="ci-check-refresh" id="refresh-pull-checks" type="button">Refresh checks</button>
|
||||
<div class="ci-check-list" id="pull-check-list"></div>
|
||||
<section class="ci-check-recovery" id="pull-check-recovery" aria-labelledby="pull-check-recovery-title" hidden>
|
||||
<h3 id="pull-check-recovery-title" tabindex="-1">Failed check</h3>
|
||||
<div id="pull-check-recovery-status" class="small" role="status" aria-live="assertive"></div>
|
||||
<pre class="ci-check-log" id="pull-check-log" tabindex="0"></pre>
|
||||
<div class="ci-check-recovery-actions">
|
||||
<button id="retry-pull-check" type="button" disabled>Retry failed job</button>
|
||||
<button id="close-pull-check-recovery" type="button">Close details</button>
|
||||
</div>
|
||||
</section>
|
||||
</details>
|
||||
<div class="pull-review-tools"><span id="pull-review-progress" class="small" aria-live="polite">Review progress unavailable.</span><button id="next-unreviewed-pull-file" type="button" disabled>Next unreviewed</button></div>
|
||||
<div id="pull-files"></div>
|
||||
@@ -1733,6 +1791,8 @@
|
||||
<details class="pull-review-request" id="pull-review-request">
|
||||
<summary>Request review</summary>
|
||||
<div>
|
||||
<button id="publish-draft-pull" type="button" hidden>Ready for review</button>
|
||||
<div id="publish-draft-pull-status" class="small" aria-live="assertive"></div>
|
||||
<button id="load-pull-reviewers" type="button">Choose reviewer</button>
|
||||
<label for="pull-review-recipient" class="small">Eligible repository reviewer</label>
|
||||
<select id="pull-review-recipient" disabled><option value="">Select a teammate</option></select>
|
||||
@@ -1750,6 +1810,20 @@
|
||||
<div id="pull-handoff-status" class="small" aria-live="assertive">Load teammates to transfer ownership.</div>
|
||||
</div>
|
||||
</details>
|
||||
<details class="pull-lifecycle" id="pull-lifecycle" hidden>
|
||||
<summary>Close pull request</summary>
|
||||
<div>
|
||||
<p class="small">Close an obsolete pull request without deleting its branch or discussion.</p>
|
||||
<button id="close-authored-pull" type="button" hidden>Close pull request</button>
|
||||
<div id="pull-lifecycle-status" class="small" role="status" aria-live="assertive"></div>
|
||||
</div>
|
||||
</details>
|
||||
<section class="pull-close-receipt" id="pull-close-receipt" aria-labelledby="pull-close-receipt-title" hidden>
|
||||
<h3 id="pull-close-receipt-title" tabindex="-1">Pull request closed.</h3>
|
||||
<p class="small">This pull request was removed from active work. Reopen it if the close was accidental.</p>
|
||||
<button id="reopen-authored-pull" type="button">Reopen pull request</button>
|
||||
<div id="pull-reopen-status" class="small" role="status" aria-live="assertive"></div>
|
||||
</section>
|
||||
<div class="pull-sheet-actions">
|
||||
<button class="share-work-route" type="button">Share</button>
|
||||
<button id="watch-pull-detail" type="button">Watch pull request</button>
|
||||
@@ -2053,6 +2127,7 @@
|
||||
<button data-mobile-queue="update" type="button" aria-label="Updates, 0 unread conversations"><span><strong>Updates</strong><small>Unread conversations</small></span><span data-mobile-queue-count="update">0</span></button>
|
||||
<button data-mobile-queue="following" type="button" aria-label="Following, 0 unseen changes"><span><strong>Following</strong><small>Issues and pull requests you watch</small></span><span data-mobile-queue-count="following">0</span></button>
|
||||
<button data-mobile-queue="filed" type="button"><span><strong>Filed</strong><small>Issues you delegated</small></span><span data-mobile-queue-count="filed">0</span></button>
|
||||
<button data-mobile-queue="authored" type="button"><span><strong>My PRs</strong><small>Pull requests you authored</small></span><span data-mobile-queue-count="authored">0</span></button>
|
||||
<button data-mobile-queue="later" type="button"><span><strong>Later</strong><small>Deferred work</small></span><span data-mobile-queue-count="later">0</span></button>
|
||||
<button data-mobile-queue="draft" type="button"><span><strong>Drafts</strong><small>Unfiled captures</small></span><span data-mobile-queue-count="draft">0</span></button>
|
||||
<button data-mobile-queue="find" type="button"><span><strong>Find Work</strong><small>Claim something new</small></span></button>
|
||||
@@ -2109,6 +2184,34 @@
|
||||
<button class="mobile-task-action" data-mobile-task="queues" type="button" aria-label="Queues: no active queues; no upcoming deadlines"><span>Queues <span class="mobile-task-count" id="mobile-queue-count" hidden>0 active</span></span><span class="mobile-task-deadline" id="mobile-deadline-count" hidden>0 due</span></button>
|
||||
</nav>
|
||||
|
||||
<div class="create-pull-sheet" id="create-pull-sheet" role="dialog" aria-modal="true" aria-labelledby="create-pull-heading" hidden>
|
||||
<section class="create-pull-panel">
|
||||
<header class="create-pull-header">
|
||||
<div><span class="eyebrow">New</span><h3 id="create-pull-heading">Pull request</h3></div>
|
||||
<button id="cancel-create-pull" type="button">Cancel</button>
|
||||
</header>
|
||||
<p class="small">Open a pull request from a branch already pushed to Gitea.</p>
|
||||
<form id="create-pull-form">
|
||||
<label for="create-pull-repository">Repository
|
||||
<select id="create-pull-repository" required><option value="">Choose repository</option></select>
|
||||
</label>
|
||||
<div class="create-pull-branches">
|
||||
<label for="create-pull-head">Source branch<select id="create-pull-head" required disabled></select></label>
|
||||
<label for="create-pull-base">Base branch<select id="create-pull-base" required disabled></select></label>
|
||||
</div>
|
||||
<output id="create-pull-head-receipt" class="small" aria-live="polite"></output>
|
||||
<label for="create-pull-title">Title<input id="create-pull-title" maxlength="255" required autocomplete="off" /></label>
|
||||
<label for="create-pull-body">Context <span class="small">Optional · Markdown</span><textarea id="create-pull-body" maxlength="10000" rows="5"></textarea></label>
|
||||
<fieldset class="create-pull-mode"><legend>Start as</legend>
|
||||
<label><input type="radio" name="create-pull-mode" value="draft" checked /> Draft</label>
|
||||
<label><input type="radio" name="create-pull-mode" value="ready" /> Ready for review</label>
|
||||
</fieldset>
|
||||
<p id="create-pull-status" role="status" aria-live="polite"></p>
|
||||
<button id="submit-create-pull" type="submit" disabled>Create draft pull request</button>
|
||||
</form>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div class="footer">Creative AI-imbued UI • stackchain-dashboard</div>
|
||||
|
||||
<script src="static/private-data-registry.js"></script>
|
||||
@@ -2197,6 +2300,7 @@
|
||||
<script src="static/voice-issue-capture.js"></script>
|
||||
<script src="static/voice-conversation-capture.js"></script>
|
||||
<script src="static/create-issue-sheet.js"></script>
|
||||
<script src="static/create-pull-sheet.js"></script>
|
||||
<script src="static/mobile-create-issue-nav.js"></script>
|
||||
<script src="static/create-and-start.js"></script>
|
||||
<script src="static/assign-and-start.js"></script>
|
||||
|
||||
+1
-1
@@ -119,7 +119,7 @@
|
||||
return;
|
||||
}
|
||||
if (reason === 'session-idle') {
|
||||
status.textContent = 'Stackchain locked after inactivity. Your drafts and queued work are still on this device. Sign in to resume.';
|
||||
status.textContent = 'Stackchain locked. Your drafts and queued work are still on this device. Sign in to resume.';
|
||||
return;
|
||||
}
|
||||
if (reason !== 'session-revoked') return;
|
||||
|
||||
@@ -8,12 +8,25 @@
|
||||
let active = false;
|
||||
let previous = '#/my-work';
|
||||
let retries = 0;
|
||||
let backgroundInert = null;
|
||||
|
||||
function attr(element, name, value) {
|
||||
if (value === null) element.removeAttribute(name);
|
||||
else element.setAttribute(name, value);
|
||||
}
|
||||
|
||||
function containBackground() {
|
||||
if (backgroundInert) return;
|
||||
backgroundInert = new Map(o.backgrounds.map(element => [element, element.inert]));
|
||||
backgroundInert.forEach((_wasInert, element) => { element.inert = true; });
|
||||
}
|
||||
|
||||
function releaseBackground() {
|
||||
if (!backgroundInert) return;
|
||||
backgroundInert.forEach((wasInert, element) => { element.inert = wasInert; });
|
||||
backgroundInert = null;
|
||||
}
|
||||
|
||||
function render(open, focus = false) {
|
||||
const wasActive = active;
|
||||
active = Boolean(open && o.mediaQuery.matches);
|
||||
@@ -28,7 +41,8 @@
|
||||
attr(o.root, 'aria-modal', active ? 'true' : null);
|
||||
attr(o.root, 'aria-hidden', active || !o.mediaQuery.matches ? null : 'true');
|
||||
o.root.inert = !active && o.mediaQuery.matches;
|
||||
o.backgrounds.forEach(element => { element.inert = active; });
|
||||
if (active) containBackground();
|
||||
else releaseBackground();
|
||||
o.dock.hidden = active;
|
||||
attr(o.hud, 'data-overlay-hidden', active ? 'true' : null);
|
||||
if (active) o.closeButton.focus();
|
||||
|
||||
+6
-1
@@ -71,6 +71,7 @@ function buildMyWork(data, now = new Date()) {
|
||||
const assigned = (item.assignees || []).includes(login);
|
||||
const isReview = (item.work_reasons || []).includes('review_requested');
|
||||
const isFiled = (item.work_reasons || []).includes('created_by_me');
|
||||
const isAuthored = (item.work_reasons || []).includes('authored_by_me');
|
||||
const isCompleted = isFiled && item.state === 'closed';
|
||||
const due = item.kind === 'issue' ? issueDueState(item.due_date, now) : null;
|
||||
const normalized = {
|
||||
@@ -78,6 +79,7 @@ function buildMyWork(data, now = new Date()) {
|
||||
key: (item.repository || 'unknown') + '#' + item.number,
|
||||
is_review: isReview,
|
||||
is_filed: isFiled,
|
||||
is_authored: isAuthored,
|
||||
is_completed: isCompleted,
|
||||
is_assigned: assigned,
|
||||
has_update: false,
|
||||
@@ -85,7 +87,8 @@ function buildMyWork(data, now = new Date()) {
|
||||
reason: priorityLabel ? priorityLabel + ' priority' :
|
||||
(due && due.priority < 4 ? due.label :
|
||||
(isReview ? 'Needs your review' : (isCompleted ? 'Completed · review outcome' :
|
||||
(assigned ? 'Assigned to you' : (isFiled ? 'Filed by you' : 'Open work'))))),
|
||||
(assigned ? 'Assigned to you' : (isFiled ? 'Filed by you' :
|
||||
(isAuthored ? 'Authored by you' : 'Open work')))))),
|
||||
_priority: priorityLabel ? 0 :
|
||||
(due && due.priority < 4 ? due.priority : (isReview ? 3 : (isCompleted ? 3.5 : (assigned ? 4 : 5)))),
|
||||
};
|
||||
@@ -657,6 +660,7 @@ function filterMyWork(items, selectedFilter, selectedMilestone = 'all') {
|
||||
let filtered = items;
|
||||
if (selectedFilter === 'attention') filtered = items.filter(needsAttention);
|
||||
else if (selectedFilter === 'filed') filtered = items.filter((item) => item.is_filed);
|
||||
else if (selectedFilter === 'authored') filtered = items.filter((item) => item.is_authored);
|
||||
else if (selectedFilter === 'review') filtered = items.filter((item) => item.is_review);
|
||||
else if (selectedFilter === 'update') filtered = items.filter((item) => item.has_update);
|
||||
else if (selectedFilter !== 'all') filtered = items.filter((item) => item.kind === selectedFilter);
|
||||
@@ -1080,6 +1084,7 @@ function countMyWork(items) {
|
||||
all: items.length,
|
||||
attention: items.filter(needsAttention).length,
|
||||
filed: items.filter((item) => item.is_filed).length,
|
||||
authored: items.filter((item) => item.is_authored).length,
|
||||
issue: items.filter((item) => item.kind === 'issue').length,
|
||||
pull: items.filter((item) => item.kind === 'pull' && !item.is_review).length,
|
||||
review: items.filter((item) => item.is_review).length,
|
||||
|
||||
+800
-11
@@ -12,12 +12,107 @@ function mergeEligibility(detail, reviewState) {
|
||||
'CI blocked by ' + blockers.join(', ') : 'CI must succeed before merging' };
|
||||
}
|
||||
if (!detail.head_sha) return { allowed: false, reason: 'Current head is unavailable' };
|
||||
const reviewer = (detail.reviewers || []).find(item => item?.blocking);
|
||||
if (reviewer?.status === 'waiting') {
|
||||
return { allowed: false, reason: 'Waiting for @' + reviewer.login + '’s review' };
|
||||
}
|
||||
if (reviewer?.status === 'changes_requested') {
|
||||
return { allowed: false, reason: '@' + reviewer.login + ' requested changes' };
|
||||
}
|
||||
if (reviewer?.status === 'outdated') {
|
||||
return { allowed: false, reason: '@' + reviewer.login + '’s review is outdated after new commits' };
|
||||
}
|
||||
if (reviewState && !reviewState.complete) {
|
||||
return { allowed: false, reason: 'Review every changed file before merging' };
|
||||
}
|
||||
return { allowed: true, reason: 'Ready to merge' };
|
||||
}
|
||||
|
||||
function renderReviewerFeedback(reviewer, escapeHtml) {
|
||||
const groups = new Map();
|
||||
(Array.isArray(reviewer?.comments) ? reviewer.comments : []).forEach(comment => {
|
||||
if (!comment?.path || !comment?.body) return;
|
||||
if (!groups.has(comment.path)) groups.set(comment.path, []);
|
||||
groups.get(comment.path).push(comment);
|
||||
});
|
||||
const summary = reviewer?.summary ? '<p class="pull-review-feedback-summary">' +
|
||||
escapeHtml(reviewer.summary) + '</p>' : '';
|
||||
const files = Array.from(groups.entries()).map(([path, comments]) =>
|
||||
'<section class="pull-review-feedback-file"><h4>' + escapeHtml(path) + '</h4><ul>' +
|
||||
comments.map(comment => '<li>' + escapeHtml(comment.body) +
|
||||
(comment.line ? '<small>Line ' + Number(comment.line) + '</small>' : '') + '</li>').join('') +
|
||||
'</ul><button type="button" data-review-feedback-file="' + escapeHtml(path) +
|
||||
'">View in changes</button></section>'
|
||||
).join('');
|
||||
const loadable = Number.isInteger(reviewer?.review_id) && reviewer.review_id > 0 &&
|
||||
['commented', 'changes_requested', 'outdated'].includes(reviewer?.status);
|
||||
const feedbackState = Array.isArray(reviewer?.comments) ? 'loaded' : reviewer?.feedback_state;
|
||||
const feedbackAction = !loadable || feedbackState === 'loaded' ? '' :
|
||||
feedbackState === 'loading' ? '<p class="small" role="status">Loading inline feedback…</p>' :
|
||||
'<p class="small" role="status">' + (feedbackState === 'error' ? 'Feedback unavailable. ' : '') +
|
||||
'<button type="button" data-load-review-feedback="' + Number(reviewer.review_id) + '">' +
|
||||
(feedbackState === 'error' ? 'Retry feedback' : 'Load inline feedback') + '</button></p>';
|
||||
const emptyLoaded = loadable && feedbackState === 'loaded' && !files ?
|
||||
'<p class="small">No inline comments on this review.</p>' : '';
|
||||
if (!summary && !files && !feedbackAction && !emptyLoaded) return '';
|
||||
const reviewedHead = reviewer?.status === 'outdated' && reviewer?.head_sha ?
|
||||
'<p class="small">Reviewed head ' + escapeHtml(reviewer.head_sha.slice(0, 8)) + '</p>' : '';
|
||||
const addressable = Number.isInteger(reviewer?.review_id) && reviewer.review_id > 0 &&
|
||||
['changes_requested', 'outdated'].includes(reviewer?.status) && feedbackState === 'loaded' &&
|
||||
(reviewer.comments || []).some(comment => Number.isInteger(comment?.id) && comment.id > 0);
|
||||
const address = addressable ? '<button type="button" class="address-review-feedback" data-address-review-feedback="' +
|
||||
Number(reviewer.review_id) + '">Address feedback</button>' : '';
|
||||
return '<details class="pull-review-feedback"><summary>Review feedback</summary>' +
|
||||
reviewedHead + summary + feedbackAction + emptyLoaded + files + address + '</details>';
|
||||
}
|
||||
|
||||
function renderReviewerStatuses(reviewers, escapeHtml) {
|
||||
const labels = {
|
||||
waiting: 'Waiting for review',
|
||||
approved: 'Approved current head',
|
||||
changes_requested: 'Changes requested',
|
||||
commented: 'Commented',
|
||||
outdated: 'Outdated after new commits',
|
||||
};
|
||||
return (Array.isArray(reviewers) ? reviewers : []).map(reviewer => {
|
||||
const status = labels[reviewer?.status] || 'Status unavailable';
|
||||
const cancel = reviewer?.status === 'waiting' && reviewer?.login ?
|
||||
'<button type="button" class="cancel-review-request" data-cancel-review-request="' +
|
||||
escapeHtml(reviewer.login) + '">Cancel request</button>' : '';
|
||||
return '<article class="pull-reviewer-status" data-reviewer-status="' +
|
||||
escapeHtml(reviewer?.status || 'unknown') + '" data-review-id="' +
|
||||
(Number.isInteger(reviewer?.review_id) ? Number(reviewer.review_id) : '') +
|
||||
'"><div class="pull-reviewer-status-heading"><strong>@' +
|
||||
escapeHtml(reviewer?.login || 'unknown') + '</strong><span>' + escapeHtml(status) + '</span></div>' +
|
||||
renderReviewerFeedback(reviewer, escapeHtml) + cancel + '</article>';
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderReviewerPanel(doc, detail, escapeHtml = value => String(value)
|
||||
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')) {
|
||||
const reviewers = Array.isArray(detail?.reviewers) ? detail.reviewers : [];
|
||||
const openFeedback = new Set(Array.from(doc.querySelectorAll('.pull-review-feedback[open]'))
|
||||
.map(panel => panel.closest('.pull-reviewer-status')?.dataset.reviewId).filter(Boolean));
|
||||
doc.querySelector('#pull-reviewer-statuses').innerHTML = renderReviewerStatuses(reviewers, escapeHtml);
|
||||
openFeedback.forEach(reviewId => {
|
||||
const panel = doc.querySelector('.pull-reviewer-status[data-review-id="' + reviewId + '"] .pull-review-feedback');
|
||||
if (panel) panel.open = true;
|
||||
});
|
||||
doc.querySelectorAll('[data-review-feedback-file]').forEach(button => {
|
||||
button.addEventListener('click', () => focusPullFile(doc, button.dataset.reviewFeedbackFile));
|
||||
});
|
||||
doc.querySelector('#pull-reviewer-status').textContent = reviewers.length ?
|
||||
reviewers.length + ' reviewer status' + (reviewers.length === 1 ? '' : 'es') + ' for this pull request.' :
|
||||
'No review has been requested; existing merge policy is unchanged.';
|
||||
doc.querySelector('#request-updated-pull-review').hidden =
|
||||
!reviewers.some(reviewer => reviewer.status === 'outdated');
|
||||
}
|
||||
|
||||
function reviewEligibility(detail, reviewState, doc) {
|
||||
renderReviewerPanel(doc, detail);
|
||||
return mergeEligibility(detail, reviewState);
|
||||
}
|
||||
|
||||
function renderFile(file, index, reviewed, escapeHtml) {
|
||||
const filename = escapeHtml(file.filename || 'Unknown file');
|
||||
const panelId = 'pull-diff-' + index;
|
||||
@@ -41,18 +136,22 @@ function renderFile(file, index, reviewed, escapeHtml) {
|
||||
'" aria-pressed="' + String(reviewed) + '">' + (reviewed ? 'Reviewed' : 'Mark reviewed') + '</button></article>';
|
||||
}
|
||||
|
||||
function focusNextUnreviewed(doc, detail, state, controller) {
|
||||
if (!detail || !state) return;
|
||||
const filename = controller.nextUnreviewed(detail, state);
|
||||
function focusPullFile(doc, filename) {
|
||||
const article = Array.from(doc.querySelectorAll('#pull-files .pull-file'))
|
||||
.find(file => file.dataset.pullFilename === filename);
|
||||
const toggle = article?.querySelector('.pull-file-toggle');
|
||||
const panel = toggle && doc.getElementById(toggle.getAttribute('aria-controls'));
|
||||
if (!toggle || !panel) return;
|
||||
if (!toggle || !panel) return false;
|
||||
toggle.setAttribute('aria-expanded', 'true');
|
||||
panel.hidden = false;
|
||||
toggle.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||
toggle.focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
function focusNextUnreviewed(doc, detail, state, controller) {
|
||||
if (!detail || !state) return;
|
||||
focusPullFile(doc, controller.nextUnreviewed(detail, state));
|
||||
}
|
||||
|
||||
function removeFromSnapshot(data, item) {
|
||||
@@ -88,17 +187,28 @@ function ownershipExitMessage(item, action, transitionResult) {
|
||||
'. Next work item opened.' : '. Choose the next ready Today item.');
|
||||
}
|
||||
|
||||
function resetOwnershipControls(doc, item, checkpointed) {
|
||||
function applyOwnershipCapabilities(doc, capabilities = null) {
|
||||
const ownership = doc.querySelector('#pull-ownership');
|
||||
const assigned = capabilities?.assigned !== false;
|
||||
ownership.hidden = !assigned;
|
||||
ownership.inert = !assigned;
|
||||
return assigned;
|
||||
}
|
||||
|
||||
function resetOwnershipControls(doc, item, checkpointed, capabilities = null) {
|
||||
const qs = selector => doc.querySelector(selector);
|
||||
const assigned = applyOwnershipCapabilities(doc, capabilities);
|
||||
resetLifecycleControls(doc, null);
|
||||
qs('#pull-ownership').open = false;
|
||||
qs('#pull-handoff-recipient').innerHTML = '<option value="">Select a teammate</option>';
|
||||
qs('#pull-handoff-recipient').disabled = true;
|
||||
qs('#confirm-pull-handoff').disabled = true;
|
||||
qs('#confirm-pull-handoff').textContent = checkpointed(item) ? 'Hand off & next' : 'Confirm handoff';
|
||||
qs('#load-pull-handoff').disabled = false;
|
||||
qs('#release-pull').disabled = false;
|
||||
qs('#load-pull-handoff').disabled = !assigned;
|
||||
qs('#release-pull').disabled = !assigned;
|
||||
qs('#release-pull').textContent = checkpointed(item) ? 'Release & next' : 'Release assignment';
|
||||
qs('#pull-handoff-status').textContent = 'Load teammates to transfer ownership.';
|
||||
qs('#pull-handoff-status').textContent = assigned ?
|
||||
'Load teammates to transfer ownership.' : 'Assignment controls are not available for this pull request.';
|
||||
qs('#edit-pull-content').hidden = true;
|
||||
qs('#pull-edit-form').hidden = true;
|
||||
qs('#pull-edit-status').textContent = '';
|
||||
@@ -114,18 +224,140 @@ function resetReviewRequestControls(doc, detail) {
|
||||
qs('#load-pull-reviewers').disabled = !detail?.head_sha;
|
||||
qs('#pull-review-request-status').textContent = detail?.head_sha ?
|
||||
'Load teammates to request a review.' : 'Load the current pull request before requesting review.';
|
||||
qs('#pull-reviewer-status').textContent = 'Reviewer status not loaded.';
|
||||
qs('#pull-reviewer-statuses').textContent = '';
|
||||
qs('#request-updated-pull-review').hidden = true;
|
||||
qs('#pull-feedback-pass').hidden = true;
|
||||
qs('#pull-feedback-status').textContent = '';
|
||||
}
|
||||
|
||||
function bindReviewRequestControls(doc, controller, getSelected) {
|
||||
function resetBranchUpdateControls(doc, detail) {
|
||||
const panel = doc.querySelector('#pull-branch-update');
|
||||
if (!panel) return;
|
||||
const eligible = detail?.capabilities?.authored === true && detail?.state === 'open' &&
|
||||
detail?.draft !== true && detail?.merged !== true && detail?.mergeable === false && detail?.head_sha;
|
||||
panel.hidden = !eligible;
|
||||
doc.querySelector('#update-pull-branch').disabled = false;
|
||||
doc.querySelector('#pull-branch-update-status').textContent = eligible ?
|
||||
'Merge the latest base branch into this pull request. Reviews and checks may run again.' : '';
|
||||
}
|
||||
|
||||
function bindBranchUpdateControls(doc, controller, getSelected, getDetail) {
|
||||
const button = doc.querySelector('#update-pull-branch');
|
||||
if (!button || button.dataset.bound === 'true') return;
|
||||
button.dataset.bound = 'true';
|
||||
button.addEventListener('click', async () => {
|
||||
const item = getSelected?.();
|
||||
const detail = getDetail?.();
|
||||
if (!item || !detail?.head_sha || detail?.capabilities?.authored !== true ||
|
||||
!globalThis.confirm('Update ' + item.key + ' with the latest base branch? Reviews and checks may run again.')) return;
|
||||
button.disabled = true;
|
||||
const status = doc.querySelector('#pull-branch-update-status');
|
||||
status.textContent = 'Updating branch…';
|
||||
try {
|
||||
const result = await controller.updateBranch(item, detail.head_sha);
|
||||
if (getSelected?.() !== item || getDetail?.() !== detail) return;
|
||||
Object.assign(detail, result, { mergeable:null, ci_state:'pending', reviewers:[] });
|
||||
status.textContent = 'Branch updated. Refreshing checks and review state…';
|
||||
doc.querySelector('#pull-review-retry')?.click();
|
||||
status.textContent = 'Branch updated to ' + result.head_sha.slice(0, 8) + '. Review the refreshed checks before merging.';
|
||||
button.hidden = true;
|
||||
doc.querySelector('#refresh-pull-checks')?.focus();
|
||||
} catch (error) {
|
||||
status.textContent = error.message + ' Reload the latest pull request state before retrying.';
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function bindReviewRequestControls(doc, controller, getSelected, getDetail, getLogin) {
|
||||
const qs = selector => doc.querySelector(selector);
|
||||
const load = qs('#load-pull-reviewers');
|
||||
if (load.dataset.reviewRequestBound === 'true') return;
|
||||
load.dataset.reviewRequestBound = 'true';
|
||||
controller.setReviewDetail = detail => {
|
||||
resetReviewRequestControls(doc, detail);
|
||||
resetBranchUpdateControls(doc, detail);
|
||||
applyOwnershipCapabilities(doc, detail?.capabilities);
|
||||
resetLifecycleControls(doc, detail?.saved_at ? null : detail);
|
||||
controller.edit?.setDetail(detail, Boolean(detail?.saved_at));
|
||||
const publishable = detail?.state === 'open' && detail?.draft === true &&
|
||||
detail?.author === getLogin?.() && detail?.head_sha;
|
||||
qs('#publish-draft-pull').hidden = !publishable;
|
||||
if (publishable) qs('#pull-review-request').open = true;
|
||||
qs('#publish-draft-pull-status').textContent = '';
|
||||
};
|
||||
resetReviewRequestControls(doc, null);
|
||||
qs('#request-updated-pull-review').addEventListener('click', () => {
|
||||
qs('#pull-review-request').open = true;
|
||||
qs('#pull-review-request').scrollIntoView({ block:'center', behavior:'smooth' });
|
||||
load.focus();
|
||||
});
|
||||
controller.onReviewRequested = result => {
|
||||
const detail = getDetail?.();
|
||||
if (!detail || result.head_sha !== detail.head_sha) return;
|
||||
detail.reviewers = (detail.reviewers || []).filter(reviewer => reviewer.login !== result.reviewer);
|
||||
detail.reviewers.push({login:result.reviewer, status:'waiting', head_sha:result.head_sha, blocking:true});
|
||||
renderReviewerPanel(doc, detail);
|
||||
qs('#pull-merge-state').textContent = 'Waiting for @' + result.reviewer + '’s review';
|
||||
qs('#merge-pull').disabled = true;
|
||||
};
|
||||
qs('#publish-draft-pull').addEventListener('click', async () => {
|
||||
const selected = getSelected?.();
|
||||
const detail = getDetail?.();
|
||||
if (!selected || !detail?.head_sha || detail.draft !== true ||
|
||||
!globalThis.confirm('Publish ' + selected.key + ' as ready for review?')) return;
|
||||
const button = qs('#publish-draft-pull');
|
||||
button.disabled = true;
|
||||
qs('#publish-draft-pull-status').textContent = 'Publishing draft…';
|
||||
try {
|
||||
const result = await controller.publishReady(selected, detail.head_sha);
|
||||
if (getSelected?.() !== selected || getDetail?.() !== detail) return;
|
||||
Object.assign(detail, result);
|
||||
selected.title = result.title;
|
||||
qs('#pull-sheet-title').textContent = result.title;
|
||||
controller.setReviewDetail(detail);
|
||||
qs('#publish-draft-pull-status').textContent = 'Published and ready for review.';
|
||||
qs('#pull-review-request').open = true;
|
||||
load.focus();
|
||||
} catch (error) {
|
||||
qs('#publish-draft-pull-status').textContent = error.message + ' The pull request remains a draft; retry.';
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}
|
||||
});
|
||||
qs('#pull-reviewer-statuses').addEventListener('click', async event => {
|
||||
const button = event.target.closest?.('[data-cancel-review-request]');
|
||||
if (!button || button.disabled) return;
|
||||
const selected = getSelected?.();
|
||||
const detail = getDetail?.();
|
||||
const reviewer = button.dataset.cancelReviewRequest;
|
||||
if (!selected || !detail?.head_sha || !reviewer ||
|
||||
!globalThis.confirm('Cancel @' + reviewer + '’s review request for ' + selected.key + '?')) return;
|
||||
button.disabled = true;
|
||||
qs('#pull-reviewer-status').textContent = 'Cancelling @' + reviewer + '’s review request…';
|
||||
try {
|
||||
const result = await controller.cancelReview(selected, reviewer, detail.head_sha);
|
||||
if (result?.head_sha !== detail.head_sha || result?.requested_reviewers?.includes(reviewer)) {
|
||||
throw new Error('Cancellation was not confirmed.');
|
||||
}
|
||||
detail.reviewers = (detail.reviewers || []).filter(candidate =>
|
||||
candidate.login !== reviewer || candidate.status !== 'waiting');
|
||||
renderReviewerPanel(doc, detail);
|
||||
const eligibility = mergeEligibility(detail, controller.reviewState(selected, detail));
|
||||
qs('#pull-merge-state').textContent = eligibility.reason;
|
||||
qs('#merge-pull').disabled = !eligibility.allowed;
|
||||
qs('#pull-review-request').open = true;
|
||||
qs('#pull-review-request-status').textContent = 'Review request cancelled. Choose a replacement reviewer.';
|
||||
load.disabled = false;
|
||||
load.focus();
|
||||
} catch (error) {
|
||||
qs('#pull-reviewer-status').textContent = error.message + ' Refresh review data before retrying.';
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}
|
||||
});
|
||||
load.addEventListener('click', async () => {
|
||||
const selected = getSelected();
|
||||
if (!selected) return;
|
||||
@@ -169,6 +401,218 @@ function bindReviewRequestControls(doc, controller, getSelected) {
|
||||
});
|
||||
}
|
||||
|
||||
function bindFeedbackControls(doc, controller, getSelected, getDetail, getLogin) {
|
||||
const qs = selector => doc.querySelector(selector);
|
||||
const panel = qs('#pull-feedback-pass');
|
||||
if (panel.dataset.feedbackBound === 'true') return;
|
||||
panel.dataset.feedbackBound = 'true';
|
||||
let active = null;
|
||||
const comments = () => (active?.reviewer?.comments || [])
|
||||
.filter(comment => Number.isInteger(comment?.id) && comment.id > 0);
|
||||
const current = () => comments()[active?.state?.index || 0];
|
||||
const save = () => {
|
||||
if (active) controller.saveFeedbackPass(active.item, active.detail, active.reviewer, active.login, active.state);
|
||||
};
|
||||
const render = () => {
|
||||
if (!active) return;
|
||||
const items = comments();
|
||||
active.state.index = Math.max(0, Math.min(Number(active.state.index) || 0, items.length - 1));
|
||||
const comment = current();
|
||||
const response = active.state.responses[String(comment.id)] || {};
|
||||
qs('#pull-feedback-progress').textContent = 'Comment ' + (active.state.index + 1) + ' of ' + items.length;
|
||||
qs('#pull-feedback-heading').textContent = 'Address @' + active.reviewer.login + '’s feedback';
|
||||
qs('#pull-feedback-location').textContent = comment.path + (comment.line ? ' · line ' + Number(comment.line) : '');
|
||||
qs('#pull-feedback-body').textContent = comment.body;
|
||||
qs('#pull-feedback-note').value = response.note || '';
|
||||
panel.querySelectorAll('[data-feedback-disposition]').forEach(button => {
|
||||
button.setAttribute('aria-pressed', String(button.dataset.feedbackDisposition === response.disposition));
|
||||
});
|
||||
qs('#previous-pull-feedback').disabled = active.state.index === 0;
|
||||
qs('#next-pull-feedback').disabled = active.state.index >= items.length - 1;
|
||||
qs('#finish-pull-feedback').disabled = active.state.posted === true ||
|
||||
items.some(item => !active.state.responses[String(item.id)]?.disposition);
|
||||
qs('#request-feedback-review').hidden = active.state.posted !== true;
|
||||
qs('#make-pull-feedback-fix').hidden = active.detail?.capabilities?.authored !== true ||
|
||||
active.detail?.state !== 'open' || active.detail?.merged === true || !comment.path;
|
||||
const found = focusPullFile(doc, comment.path);
|
||||
qs('#pull-feedback-context').textContent = found ?
|
||||
'Matching change opened below.' : 'Matching change is unavailable in this preview.';
|
||||
panel.scrollIntoView({ block:'center', behavior:'smooth' });
|
||||
};
|
||||
qs('#pull-reviewer-statuses').addEventListener('click', async event => {
|
||||
const loadButton = event.target.closest?.('[data-load-review-feedback]');
|
||||
if (loadButton && !loadButton.disabled) {
|
||||
const detail = getDetail?.();
|
||||
const item = getSelected?.();
|
||||
const reviewId = Number(loadButton.dataset.loadReviewFeedback);
|
||||
const reviewer = (detail?.reviewers || []).find(candidate => candidate.review_id === reviewId);
|
||||
if (!detail || !item || !reviewer) return;
|
||||
const refresh = reviewer.feedback_state === 'error';
|
||||
reviewer.feedback_state = 'loading';
|
||||
renderReviewerPanel(doc, detail);
|
||||
try {
|
||||
const result = await controller.loadFeedback(item, detail, reviewer, { refresh });
|
||||
if (getDetail?.() !== detail || getSelected?.() !== item ||
|
||||
result.head_sha !== detail.head_sha || Number(result.review_id) !== reviewId) return;
|
||||
reviewer.comments = Array.isArray(result.comments) ? result.comments : [];
|
||||
reviewer.feedback_state = 'loaded';
|
||||
renderReviewerPanel(doc, detail);
|
||||
doc.querySelector('[data-address-review-feedback="' + reviewId + '"]')?.focus();
|
||||
} catch (error) {
|
||||
if (getDetail?.() !== detail || getSelected?.() !== item) return;
|
||||
reviewer.feedback_state = 'error';
|
||||
renderReviewerPanel(doc, detail);
|
||||
doc.querySelector('[data-load-review-feedback="' + reviewId + '"]')?.focus();
|
||||
}
|
||||
return;
|
||||
}
|
||||
const button = event.target.closest?.('[data-address-review-feedback]');
|
||||
if (!button) return;
|
||||
const detail = getDetail?.();
|
||||
const item = getSelected?.();
|
||||
const reviewId = Number(button.dataset.addressReviewFeedback);
|
||||
const reviewer = (detail?.reviewers || []).find(candidate => candidate.review_id === reviewId);
|
||||
if (!detail || !item || !reviewer) return;
|
||||
const login = getLogin?.() || '';
|
||||
active = { item, detail, reviewer, login,
|
||||
state:controller.loadFeedbackPass(item, detail, reviewer, login) };
|
||||
panel.hidden = false;
|
||||
qs('#pull-feedback-file-editor').hidden = true;
|
||||
qs('#cancel-pull-feedback-fix').hidden = true;
|
||||
qs('#commit-pull-feedback-fix').hidden = true;
|
||||
active.file = null;
|
||||
qs('#pull-feedback-status').textContent = active.state.posted ?
|
||||
'Response already posted. You can request an updated review.' : 'Progress saves on this device.';
|
||||
render();
|
||||
});
|
||||
qs('#make-pull-feedback-fix').addEventListener('click', async () => {
|
||||
const comment = current();
|
||||
if (!active || !comment?.path || active.detail?.capabilities?.authored !== true) return;
|
||||
const button = qs('#make-pull-feedback-fix');
|
||||
button.disabled = true;
|
||||
qs('#pull-feedback-status').textContent = 'Loading the current pull file…';
|
||||
try {
|
||||
const file = await controller.loadFeedbackFile(active.item, comment.path, active.detail.head_sha);
|
||||
if (!active || file.head_sha !== active.detail.head_sha || file.path !== comment.path) return;
|
||||
active.file = file;
|
||||
qs('#pull-feedback-file-path').textContent = file.path;
|
||||
qs('#pull-feedback-file-content').value = file.content;
|
||||
qs('#pull-feedback-commit-message').value = 'fix: address review feedback';
|
||||
qs('#pull-feedback-file-editor').hidden = false;
|
||||
qs('#cancel-pull-feedback-fix').hidden = false;
|
||||
qs('#commit-pull-feedback-fix').hidden = false;
|
||||
qs('#pull-feedback-status').textContent = 'Edit the bounded file, then commit it to this pull branch.';
|
||||
qs('#pull-feedback-file-content').focus();
|
||||
} catch (error) {
|
||||
qs('#pull-feedback-status').textContent = error.message + ' Retry without losing your feedback progress.';
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
qs('#cancel-pull-feedback-fix').addEventListener('click', () => {
|
||||
qs('#pull-feedback-file-editor').hidden = true;
|
||||
qs('#cancel-pull-feedback-fix').hidden = true;
|
||||
qs('#commit-pull-feedback-fix').hidden = true;
|
||||
active.file = null;
|
||||
qs('#make-pull-feedback-fix').focus();
|
||||
});
|
||||
qs('#commit-pull-feedback-fix').addEventListener('click', async () => {
|
||||
if (!active?.file) return;
|
||||
const content = qs('#pull-feedback-file-content').value;
|
||||
const message = qs('#pull-feedback-commit-message').value.trim();
|
||||
if (!message || content === active.file.content) {
|
||||
qs('#pull-feedback-status').textContent = 'Change the file and enter a commit message before committing.';
|
||||
return;
|
||||
}
|
||||
if (!globalThis.confirm('Commit this change to ' + active.item.key + '?')) return;
|
||||
const button = qs('#commit-pull-feedback-fix');
|
||||
button.disabled = true;
|
||||
qs('#pull-feedback-status').textContent = 'Committing and verifying the new pull head…';
|
||||
try {
|
||||
const result = await controller.commitFeedbackFix(active.item, {
|
||||
path:active.file.path, content, message,
|
||||
expectedHeadSha:active.file.head_sha, expectedBlobSha:active.file.blob_sha,
|
||||
});
|
||||
active.detail.head_sha = result.head_sha;
|
||||
active.state.headSha = result.head_sha;
|
||||
active.file = null;
|
||||
save();
|
||||
qs('#pull-feedback-file-editor').hidden = true;
|
||||
qs('#cancel-pull-feedback-fix').hidden = true;
|
||||
qs('#commit-pull-feedback-fix').hidden = true;
|
||||
qs('#pull-feedback-status').textContent = 'Code change committed. Mark the comment Addressed when satisfied.';
|
||||
render();
|
||||
} catch (error) {
|
||||
qs('#pull-feedback-status').textContent = error.message + ' Draft kept; reload if the branch changed, or retry.';
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}
|
||||
});
|
||||
panel.querySelector('.pull-feedback-dispositions').addEventListener('click', event => {
|
||||
const disposition = event.target.dataset?.feedbackDisposition;
|
||||
const comment = current();
|
||||
if (!active || !comment || !['addressed', 'discussion', 'skipped'].includes(disposition)) return;
|
||||
const key = String(comment.id);
|
||||
active.state.responses[key] = { ...(active.state.responses[key] || {}), disposition };
|
||||
save();
|
||||
render();
|
||||
});
|
||||
qs('#pull-feedback-note').addEventListener('input', event => {
|
||||
const comment = current();
|
||||
if (!active || !comment) return;
|
||||
const key = String(comment.id);
|
||||
active.state.responses[key] = { ...(active.state.responses[key] || {}), note:event.target.value.slice(0, 1000) };
|
||||
save();
|
||||
});
|
||||
qs('#previous-pull-feedback').addEventListener('click', () => {
|
||||
if (!active) return;
|
||||
active.state.index -= 1; save(); render();
|
||||
});
|
||||
qs('#next-pull-feedback').addEventListener('click', () => {
|
||||
if (!active) return;
|
||||
active.state.index += 1; save(); render();
|
||||
});
|
||||
qs('#close-pull-feedback').addEventListener('click', () => {
|
||||
panel.hidden = true;
|
||||
doc.querySelector('[data-address-review-feedback="' + active?.reviewer?.review_id + '"]')?.focus();
|
||||
});
|
||||
qs('#finish-pull-feedback').addEventListener('click', async () => {
|
||||
if (!active || qs('#finish-pull-feedback').disabled) return;
|
||||
const latest = getDetail?.();
|
||||
if (!latest || latest.head_sha !== active.state.headSha) {
|
||||
qs('#pull-feedback-status').textContent = 'The pull request changed. Refresh review data before posting.';
|
||||
return;
|
||||
}
|
||||
if (!globalThis.confirm('Post one feedback response to ' + active.item.key + '?')) return;
|
||||
qs('#finish-pull-feedback').disabled = true;
|
||||
qs('#pull-feedback-status').textContent = 'Posting feedback response…';
|
||||
try {
|
||||
await controller.postFeedbackResponse(active.item, active.detail, active.reviewer, active.login, active.state);
|
||||
active.state.posted = true;
|
||||
save();
|
||||
qs('#pull-feedback-status').textContent = 'Response posted. Request an updated review when ready.';
|
||||
render();
|
||||
} catch (error) {
|
||||
qs('#pull-feedback-status').textContent = error.message + ' Progress kept; retry without duplicating the response.';
|
||||
qs('#finish-pull-feedback').disabled = false;
|
||||
}
|
||||
});
|
||||
qs('#request-feedback-review').addEventListener('click', async () => {
|
||||
if (!active?.state?.posted) return;
|
||||
const button = qs('#request-feedback-review');
|
||||
button.disabled = true;
|
||||
qs('#pull-feedback-status').textContent = 'Requesting updated review…';
|
||||
try {
|
||||
await controller.requestReview(active.item, active.reviewer.login, active.detail.head_sha);
|
||||
qs('#pull-feedback-status').textContent = 'Response posted; updated review requested from @' + active.reviewer.login + '.';
|
||||
button.hidden = true;
|
||||
} catch (error) {
|
||||
qs('#pull-feedback-status').textContent = 'Response posted; review not requested. ' + error.message;
|
||||
button.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function bindContextEditor(doc, controller, getSelected, getDetail, getLogin) {
|
||||
const qs = selector => doc.querySelector(selector);
|
||||
const form = qs('#pull-edit-form');
|
||||
@@ -242,7 +686,11 @@ function bindContextEditor(doc, controller, getSelected, getDetail, getLogin) {
|
||||
}
|
||||
|
||||
function bindOwnershipControls(doc, controller, getSelected, finish, getDetail, getLogin) {
|
||||
bindReviewRequestControls(doc, controller, getSelected);
|
||||
bindReviewRequestControls(doc, controller, getSelected, getDetail, getLogin);
|
||||
bindBranchUpdateControls(doc, controller, getSelected, getDetail);
|
||||
bindFeedbackControls(doc, controller, getSelected, getDetail, getLogin);
|
||||
bindCheckRecovery(doc, controller, getSelected, getDetail);
|
||||
bindLifecycleControls(doc, controller, getSelected, getDetail, result => controller.onState?.(result));
|
||||
controller.edit = bindContextEditor(doc, controller, getSelected, getDetail, getLogin);
|
||||
const qs = selector => doc.querySelector(selector);
|
||||
const load = qs('#load-pull-handoff');
|
||||
@@ -308,23 +756,33 @@ function bindOwnershipControls(doc, controller, getSelected, finish, getDetail,
|
||||
});
|
||||
}
|
||||
|
||||
function createPullSheet({ fetchJson, storage, createConversationPager = globalThis.createConversationPager, createOperationId = () => globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random() }) {
|
||||
function createPullSheet({ fetchJson, storage, onState, createConversationPager = globalThis.createConversationPager, createOperationId = () => globalThis.crypto?.randomUUID?.() || String(Date.now()) + '-' + Math.random() }) {
|
||||
let commentRequest = null;
|
||||
let mergeRequest = null;
|
||||
let checkRequest = null;
|
||||
let ownershipRequest = null;
|
||||
let branchUpdateRequest = null;
|
||||
let candidateRequest = null;
|
||||
let reviewCandidateRequest = null;
|
||||
let reviewRequestMutation = null;
|
||||
let reviewCancelMutation = null;
|
||||
let readyMutation = null;
|
||||
let lifecycleMutation = null;
|
||||
let editRequest = null;
|
||||
let feedbackRequest = null;
|
||||
let feedbackFixRequest = null;
|
||||
const reviewRequests = new Map();
|
||||
const reviewCache = new Map();
|
||||
const feedbackRequests = new Map();
|
||||
const feedbackCache = new Map();
|
||||
const pathFor = item => 'api/v1/repos/' + String(item.repository || '').split('/')
|
||||
.map(encodeURIComponent).join('/') + '/pulls/' + encodeURIComponent(item.number);
|
||||
const draftKey = item => 'stackchain.pull-comment.v1:' + item.repository + '#' + item.number;
|
||||
const operationKey = item => draftKey(item) + ':operation';
|
||||
const editDraftKey = item => 'stackchain.pull-edit.v1:' + item.repository + '#' + item.number;
|
||||
const reviewKey = (item, detail) => 'stackchain.pull-review.v1:' + item.repository + '#' + item.number + ':' + detail.head_sha;
|
||||
const feedbackKey = (item, detail, reviewer, login) => 'stackchain.feedback-pass.v1:' +
|
||||
item.repository + '#' + item.number + ':' + reviewer.review_id + ':' + reviewer.head_sha + ':' + detail.head_sha + ':' + login;
|
||||
const fileNames = detail => (detail?.files || []).map(file => file.filename).filter(Boolean);
|
||||
|
||||
function reviewState(item, detail) {
|
||||
@@ -339,6 +797,7 @@ function createPullSheet({ fetchJson, storage, createConversationPager = globalT
|
||||
}
|
||||
|
||||
return {
|
||||
onState,
|
||||
load(item) {
|
||||
return fetchJson(pathFor(item) + '/detail', { headers: { Accept: 'application/json' } });
|
||||
},
|
||||
@@ -356,6 +815,49 @@ function createPullSheet({ fetchJson, storage, createConversationPager = globalT
|
||||
reviewRequests.set(key, request);
|
||||
return request;
|
||||
},
|
||||
loadFeedback(item, detail, reviewer, { refresh = false } = {}) {
|
||||
const reviewId = Number(reviewer?.review_id);
|
||||
const headSha = detail?.head_sha || '';
|
||||
const key = item.repository + '#' + item.number + ':' + headSha + ':' + reviewId;
|
||||
if (!refresh && feedbackCache.has(key)) return Promise.resolve(feedbackCache.get(key));
|
||||
if (feedbackRequests.has(key)) return feedbackRequests.get(key);
|
||||
const request = fetchJson(pathFor(item) + '/reviews/' + encodeURIComponent(reviewId) +
|
||||
'/feedback?expected_head_sha=' + encodeURIComponent(headSha), {
|
||||
headers: { Accept: 'application/json' },
|
||||
}).then(result => {
|
||||
if (result?.head_sha !== headSha || Number(result?.review_id) !== reviewId) {
|
||||
throw new Error('Review feedback changed. Reload review data before retrying.');
|
||||
}
|
||||
feedbackCache.set(key, result);
|
||||
return result;
|
||||
}).finally(() => feedbackRequests.delete(key));
|
||||
feedbackRequests.set(key, request);
|
||||
return request;
|
||||
},
|
||||
loadFeedbackFile(item, path, expectedHeadSha) {
|
||||
return fetchJson(pathFor(item) + '/feedback-file?path=' + encodeURIComponent(path) +
|
||||
'&expected_head_sha=' + encodeURIComponent(expectedHeadSha), {
|
||||
headers:{ Accept:'application/json' },
|
||||
});
|
||||
},
|
||||
commitFeedbackFix(item, draft) {
|
||||
if (feedbackFixRequest) return feedbackFixRequest;
|
||||
feedbackFixRequest = fetchJson(pathFor(item) + '/feedback-file', {
|
||||
method:'PATCH',
|
||||
headers:{ Accept:'application/json', 'Content-Type':'application/json' },
|
||||
body:JSON.stringify({
|
||||
path:draft.path, content:draft.content, message:draft.message,
|
||||
expected_head_sha:draft.expectedHeadSha,
|
||||
expected_blob_sha:draft.expectedBlobSha,
|
||||
}),
|
||||
}).then(result => {
|
||||
if (!result?.head_sha || result.head_sha === draft.expectedHeadSha || result.path !== draft.path) {
|
||||
throw new Error('The feedback fix was not confirmed.');
|
||||
}
|
||||
return result;
|
||||
}).finally(() => { feedbackFixRequest = null; });
|
||||
return feedbackFixRequest;
|
||||
},
|
||||
loadChecks(item) {
|
||||
if (checkRequest) return checkRequest;
|
||||
checkRequest = fetchJson(pathFor(item) + '/checks', {
|
||||
@@ -363,6 +865,21 @@ function createPullSheet({ fetchJson, storage, createConversationPager = globalT
|
||||
}).finally(() => { checkRequest = null; });
|
||||
return checkRequest;
|
||||
},
|
||||
loadCheckFailure(item, expectedHeadSha, runId, jobIndex) {
|
||||
return fetchJson(pathFor(item) + '/checks/' + encodeURIComponent(runId) +
|
||||
'/jobs/' + encodeURIComponent(jobIndex) + '/failure?expected_head_sha=' +
|
||||
encodeURIComponent(expectedHeadSha), {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
},
|
||||
retryCheck(item, expectedHeadSha, runId, jobIndex) {
|
||||
return fetchJson(pathFor(item) + '/checks/' + encodeURIComponent(runId) +
|
||||
'/jobs/' + encodeURIComponent(jobIndex) + '/retry', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({ expected_head_sha: expectedHeadSha }),
|
||||
});
|
||||
},
|
||||
loadHandoffCandidates(item) {
|
||||
if (candidateRequest) return candidateRequest;
|
||||
candidateRequest = fetchJson(pathFor(item) + '/handoff-candidates', {
|
||||
@@ -383,9 +900,55 @@ function createPullSheet({ fetchJson, storage, createConversationPager = globalT
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reviewer, expected_head_sha: expectedHeadSha }),
|
||||
}).then(result => {
|
||||
this.onReviewRequested?.(result);
|
||||
return result;
|
||||
}).finally(() => { reviewRequestMutation = null; });
|
||||
return reviewRequestMutation;
|
||||
},
|
||||
cancelReview(item, reviewer, expectedHeadSha) {
|
||||
if (reviewCancelMutation) return reviewCancelMutation;
|
||||
reviewCancelMutation = fetchJson(pathFor(item) + '/request-review', {
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ reviewer, expected_head_sha: expectedHeadSha }),
|
||||
}).then(result => {
|
||||
this.onReviewCancelled?.(result);
|
||||
return result;
|
||||
}).finally(() => { reviewCancelMutation = null; });
|
||||
return reviewCancelMutation;
|
||||
},
|
||||
publishReady(item, expectedHeadSha) {
|
||||
if (readyMutation) return readyMutation;
|
||||
readyMutation = fetchJson(pathFor(item) + '/ready', {
|
||||
method:'PATCH',
|
||||
headers:{ Accept:'application/json', 'Content-Type':'application/json' },
|
||||
body:JSON.stringify({ expected_head_sha:expectedHeadSha }),
|
||||
}).then(result => {
|
||||
if (result?.number !== item.number || result?.head_sha !== expectedHeadSha ||
|
||||
result?.state !== 'open' || result?.draft !== false || !result?.title) {
|
||||
throw new Error('Draft publication was not confirmed.');
|
||||
}
|
||||
return result;
|
||||
}).finally(() => { readyMutation = null; });
|
||||
return readyMutation;
|
||||
},
|
||||
transition(item, expectedHeadSha, action) {
|
||||
if (lifecycleMutation) return lifecycleMutation;
|
||||
lifecycleMutation = fetchJson(pathFor(item) + '/' + action, {
|
||||
method:'PATCH',
|
||||
headers:{ Accept:'application/json', 'Content-Type':'application/json' },
|
||||
body:JSON.stringify({ expected_head_sha:expectedHeadSha }),
|
||||
}).then(result => {
|
||||
const expectedState = action === 'close' ? 'closed' : 'open';
|
||||
if (result?.number !== item.number || result?.head_sha !== expectedHeadSha ||
|
||||
result?.state !== expectedState || result?.merged === true) {
|
||||
throw new Error('Pull request state change was not confirmed.');
|
||||
}
|
||||
return result;
|
||||
}).finally(() => { lifecycleMutation = null; });
|
||||
return lifecycleMutation;
|
||||
},
|
||||
loadEditDraft(item) {
|
||||
try {
|
||||
const value = JSON.parse(storage?.getItem(editDraftKey(item)) || 'null');
|
||||
@@ -397,6 +960,50 @@ function createPullSheet({ fetchJson, storage, createConversationPager = globalT
|
||||
try { storage?.setItem(editDraftKey(item), JSON.stringify(draft)); }
|
||||
catch (_error) { /* The edit fields remain the fallback. */ }
|
||||
},
|
||||
loadFeedbackPass(item, detail, reviewer, login) {
|
||||
const fresh = { headSha:detail.head_sha, index:0, responses:{}, posted:false };
|
||||
try {
|
||||
const saved = JSON.parse(storage?.getItem(feedbackKey(item, detail, reviewer, login)) || 'null');
|
||||
return saved && saved.headSha === detail.head_sha && saved.responses && typeof saved.responses === 'object'
|
||||
? { ...fresh, ...saved } : fresh;
|
||||
} catch (_error) { return fresh; }
|
||||
},
|
||||
saveFeedbackPass(item, detail, reviewer, login, state) {
|
||||
try { storage?.setItem(feedbackKey(item, detail, reviewer, login), JSON.stringify(state)); }
|
||||
catch (_error) { /* The visible pass remains usable without storage. */ }
|
||||
},
|
||||
feedbackSummary(reviewer, state) {
|
||||
const labels = { addressed:'Addressed', discussion:'Needs discussion', skipped:'Skip for now' };
|
||||
const lines = (reviewer.comments || []).filter(comment => Number.isInteger(comment?.id) && comment.id > 0)
|
||||
.map(comment => {
|
||||
const response = state.responses[String(comment.id)] || {};
|
||||
const path = String(comment.path || '').replaceAll('`', "'").replaceAll('\n', ' ').slice(0, 300);
|
||||
const body = String(comment.body || '').replaceAll('\n', ' ').slice(0, 180);
|
||||
const note = String(response.note || '').replaceAll('\n', ' ').slice(0, 1000);
|
||||
return '- `' + path + '` · comment #' + comment.id + ' · **' + (labels[response.disposition] || 'Unresolved') +
|
||||
'** — ' + body + (note ? '\n - Response: ' + note : '');
|
||||
});
|
||||
return ('Addressed review feedback from @' + reviewer.login + ' (review #' + reviewer.review_id + ').\n\n' +
|
||||
lines.join('\n')).slice(0, 10000);
|
||||
},
|
||||
postFeedbackResponse(item, detail, reviewer, login, state) {
|
||||
if (feedbackRequest) return feedbackRequest;
|
||||
const key = feedbackKey(item, detail, reviewer, login);
|
||||
let operationId;
|
||||
try {
|
||||
operationId = storage?.getItem(key + ':operation') || String(createOperationId()).slice(0, 128);
|
||||
storage?.setItem(key + ':operation', operationId);
|
||||
} catch (_error) { operationId = String(createOperationId()).slice(0, 128); }
|
||||
feedbackRequest = fetchJson(pathFor(item) + '/comments', {
|
||||
method:'POST',
|
||||
headers:{ Accept:'application/json', 'Content-Type':'application/json', 'Idempotency-Key':operationId },
|
||||
body:JSON.stringify({ body:this.feedbackSummary(reviewer, state) }),
|
||||
}).then(result => {
|
||||
try { storage?.removeItem(key + ':operation'); } catch (_error) { /* Confirmed upstream. */ }
|
||||
return result;
|
||||
}).finally(() => { feedbackRequest = null; });
|
||||
return feedbackRequest;
|
||||
},
|
||||
updateContent(item, draft) {
|
||||
if (editRequest) return editRequest;
|
||||
this.saveEditDraft(item, draft);
|
||||
@@ -505,14 +1112,194 @@ function createPullSheet({ fetchJson, storage, createConversationPager = globalT
|
||||
}).finally(() => { mergeRequest = null; });
|
||||
return mergeRequest;
|
||||
},
|
||||
updateBranch(item, expectedHeadSha) {
|
||||
if (branchUpdateRequest) return branchUpdateRequest;
|
||||
branchUpdateRequest = fetchJson(pathFor(item) + '/update-branch', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json', 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ expected_head_sha: expectedHeadSha }),
|
||||
}).then(result => {
|
||||
if (!result?.head_sha || result.head_sha === expectedHeadSha) {
|
||||
throw new Error('Branch update was not confirmed.');
|
||||
}
|
||||
return result;
|
||||
}).finally(() => { branchUpdateRequest = null; });
|
||||
return branchUpdateRequest;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resetLifecycleControls(doc, detail) {
|
||||
const authored = detail?.capabilities?.authored === true;
|
||||
const lifecycle = doc.querySelector('#pull-lifecycle');
|
||||
if (!lifecycle) return;
|
||||
lifecycle.hidden = !authored || detail?.state !== 'open' || detail?.merged === true;
|
||||
doc.querySelector('#close-authored-pull').hidden = !authored || detail?.state !== 'open' || detail?.merged === true;
|
||||
doc.querySelector('#pull-close-receipt').hidden = true;
|
||||
doc.querySelector('#pull-lifecycle-status').textContent = '';
|
||||
doc.querySelector('#pull-reopen-status').textContent = '';
|
||||
}
|
||||
|
||||
function bindLifecycleControls(doc, controller, selectedPull, selectedDetail, applyResult) {
|
||||
const close = doc.querySelector('#close-authored-pull');
|
||||
const reopen = doc.querySelector('#reopen-authored-pull');
|
||||
close.addEventListener('click', async () => {
|
||||
const item = selectedPull();
|
||||
const detail = selectedDetail();
|
||||
if (!item || !detail?.head_sha || detail?.capabilities?.authored !== true ||
|
||||
!globalThis.confirm('Close ' + item.key + ' at head ' + detail.head_sha.slice(0, 12) + '?')) return;
|
||||
close.disabled = true;
|
||||
doc.querySelector('#pull-lifecycle-status').textContent = 'Closing pull request…';
|
||||
try {
|
||||
const result = await controller.transition(item, detail.head_sha, 'close');
|
||||
Object.assign(detail, result);
|
||||
applyResult(result);
|
||||
doc.querySelector('#pull-lifecycle').hidden = true;
|
||||
doc.querySelector('#pull-close-receipt').hidden = false;
|
||||
doc.querySelector('#pull-lifecycle-status').textContent = '';
|
||||
doc.querySelector('#pull-close-receipt-title').focus();
|
||||
} catch (error) {
|
||||
doc.querySelector('#pull-lifecycle-status').textContent = error.message + ' The pull request remains open; reload and retry.';
|
||||
close.disabled = false;
|
||||
close.focus();
|
||||
}
|
||||
});
|
||||
reopen.addEventListener('click', async () => {
|
||||
const item = selectedPull();
|
||||
const detail = selectedDetail();
|
||||
if (!item || !detail?.head_sha) return;
|
||||
reopen.disabled = true;
|
||||
doc.querySelector('#pull-reopen-status').textContent = 'Reopening pull request…';
|
||||
try {
|
||||
const result = await controller.transition(item, detail.head_sha, 'reopen');
|
||||
Object.assign(detail, result);
|
||||
applyResult(result);
|
||||
doc.querySelector('#pull-close-receipt').hidden = true;
|
||||
doc.querySelector('#pull-lifecycle').hidden = false;
|
||||
close.hidden = false;
|
||||
close.disabled = false;
|
||||
doc.querySelector('#pull-lifecycle-status').textContent = 'Pull request reopened.';
|
||||
doc.querySelector('#pull-reopen-status').textContent = '';
|
||||
close.focus();
|
||||
} catch (error) {
|
||||
doc.querySelector('#pull-reopen-status').textContent = error.message + ' The pull request remains closed; reload and retry.';
|
||||
reopen.disabled = false;
|
||||
reopen.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function bindCheckRecovery(
|
||||
doc, controller, selectedPull, selectedDetail,
|
||||
confirmRetry = message => globalThis.confirm(message)
|
||||
) {
|
||||
let current = null;
|
||||
const get = selector => doc.querySelector(selector);
|
||||
function reset({ restoreFocus = true } = {}) {
|
||||
const recovery = current;
|
||||
current = null;
|
||||
get('#pull-check-recovery').hidden = true;
|
||||
get('#pull-check-log').textContent = '';
|
||||
get('#pull-check-recovery-status').textContent = '';
|
||||
get('#retry-pull-check').disabled = true;
|
||||
if (restoreFocus) (recovery?.trigger?.isConnected ? recovery.trigger : get('#refresh-pull-checks'))?.focus();
|
||||
}
|
||||
async function poll(recovery, attempt = 0) {
|
||||
if (current !== recovery || selectedPull() !== recovery.item) return;
|
||||
if (attempt >= 12) {
|
||||
get('#pull-check-recovery-status').textContent = 'Retry is still queued. Use Refresh checks to continue monitoring.';
|
||||
return;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 1500));
|
||||
if (current !== recovery || selectedPull() !== recovery.item) return;
|
||||
try {
|
||||
const status = await controller.loadChecks(recovery.item);
|
||||
if (current !== recovery || selectedPull() !== recovery.item) return;
|
||||
if (status.head_sha !== recovery.headSha) {
|
||||
get('#pull-check-recovery-status').textContent = 'New commits arrived. Reload the pull request before retrying again.';
|
||||
return;
|
||||
}
|
||||
const check = (status.checks || []).find(candidate =>
|
||||
candidate?.recovery?.run_id === recovery.runId && candidate?.recovery?.job_index === recovery.jobIndex
|
||||
);
|
||||
if (!check || !['failure', 'error', 'pending'].includes(check.state)) {
|
||||
get('#refresh-pull-checks').click();
|
||||
get('#pull-check-recovery-status').textContent = 'Retried check completed. Merge readiness refreshed.';
|
||||
return;
|
||||
}
|
||||
get('#pull-check-recovery-status').textContent = check.state === 'pending'
|
||||
? 'Retried check is running…' : 'Retry queued; waiting for a fresh run…';
|
||||
} catch (_error) {
|
||||
get('#pull-check-recovery-status').textContent = 'Waiting for check status…';
|
||||
}
|
||||
return poll(recovery, attempt + 1);
|
||||
}
|
||||
get('#pull-check-list').addEventListener('click', async event => {
|
||||
const trigger = event.target.closest('.ci-check-inspect');
|
||||
const item = selectedPull();
|
||||
const detail = selectedDetail();
|
||||
if (!trigger || !item || !detail?.head_sha) return;
|
||||
const runId = Number(trigger.dataset.runId);
|
||||
const jobIndex = Number(trigger.dataset.jobIndex);
|
||||
if (!Number.isInteger(runId) || !Number.isInteger(jobIndex)) return;
|
||||
const recovery = {
|
||||
item, headSha: detail.head_sha, runId, jobIndex, trigger,
|
||||
name: trigger.closest('.ci-check')?.querySelector('strong')?.textContent || 'Failed check',
|
||||
};
|
||||
current = recovery;
|
||||
get('#pull-check-recovery').hidden = false;
|
||||
get('#pull-check-recovery-title').textContent = recovery.name;
|
||||
get('#pull-check-log').textContent = 'Loading failure details…';
|
||||
get('#pull-check-recovery-status').textContent = 'Loading failure details…';
|
||||
get('#retry-pull-check').disabled = true;
|
||||
get('#pull-check-recovery-title').focus();
|
||||
try {
|
||||
const result = await controller.loadCheckFailure(item, recovery.headSha, runId, jobIndex);
|
||||
if (current !== recovery || selectedPull() !== item) return;
|
||||
get('#pull-check-log').textContent = result.excerpt || 'No failure output was reported.';
|
||||
get('#pull-check-recovery-status').textContent = 'Failure details loaded.';
|
||||
get('#retry-pull-check').disabled = false;
|
||||
} catch (error) {
|
||||
if (current !== recovery || selectedPull() !== item) return;
|
||||
get('#pull-check-log').textContent = '';
|
||||
get('#pull-check-recovery-status').textContent = error.message;
|
||||
}
|
||||
});
|
||||
get('#close-pull-check-recovery').addEventListener('click', () => reset());
|
||||
get('#pull-checks').addEventListener('toggle', () => {
|
||||
if (current && selectedPull() !== current.item) reset({ restoreFocus: false });
|
||||
});
|
||||
get('#retry-pull-check').addEventListener('click', async () => {
|
||||
const recovery = current;
|
||||
if (!recovery || selectedPull() !== recovery.item) return;
|
||||
if (!confirmRetry('Retry ' + recovery.name + ' for head ' + recovery.headSha.slice(0, 12) + '?')) return;
|
||||
const button = get('#retry-pull-check');
|
||||
button.disabled = true;
|
||||
get('#pull-check-recovery-status').textContent = 'Queueing retry…';
|
||||
try {
|
||||
await controller.retryCheck(recovery.item, recovery.headSha, recovery.runId, recovery.jobIndex);
|
||||
if (current !== recovery) return;
|
||||
get('#pull-check-recovery-status').textContent = 'Retry queued; waiting for a fresh run…';
|
||||
poll(recovery);
|
||||
} catch (error) {
|
||||
if (current !== recovery) return;
|
||||
get('#pull-check-recovery-status').textContent = error.message;
|
||||
button.disabled = false;
|
||||
button.focus();
|
||||
}
|
||||
});
|
||||
return { reset };
|
||||
}
|
||||
|
||||
createPullSheet.mergeEligibility = mergeEligibility;
|
||||
createPullSheet.review = reviewEligibility;
|
||||
createPullSheet.renderReviewerStatuses = renderReviewerStatuses;
|
||||
createPullSheet.renderFile = renderFile;
|
||||
createPullSheet.focusNextUnreviewed = focusNextUnreviewed;
|
||||
createPullSheet.removeFromSnapshot = removeFromSnapshot;
|
||||
createPullSheet.sameTarget = sameTarget;
|
||||
createPullSheet.bindLifecycleControls = bindLifecycleControls;
|
||||
createPullSheet.resetLifecycleControls = resetLifecycleControls;
|
||||
createPullSheet.ownershipSelectors = ownershipSelectors;
|
||||
createPullSheet.renderHandoffCandidates = renderHandoffCandidates;
|
||||
createPullSheet.ownershipExitMessage = ownershipExitMessage;
|
||||
@@ -521,4 +1308,6 @@ createPullSheet.bindOwnershipControls = bindOwnershipControls;
|
||||
createPullSheet.bindContextEditor = bindContextEditor;
|
||||
createPullSheet.resetReviewRequestControls = resetReviewRequestControls;
|
||||
createPullSheet.bindReviewRequestControls = bindReviewRequestControls;
|
||||
createPullSheet.bindFeedbackControls = bindFeedbackControls;
|
||||
createPullSheet.bindCheckRecovery = bindCheckRecovery;
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createPullSheet;
|
||||
+268
-5
@@ -1,8 +1,11 @@
|
||||
function createReleaseReceipt({ storage, getLogin, fetchJson, launcher = null, dialog = null, statusNode = null, checksNode = null, releaseNode = null, listNode = null, documentRef = null, windowRef = null, setTimer = setTimeout, clearTimer = clearTimeout, pollMs = 30000 }) {
|
||||
function createReleaseReceipt({ storage, getLogin, fetchJson, launcher = null, dialog = null, statusNode = null, checksNode = null, releaseNode = null, listNode = null, documentRef = null, windowRef = null, confirmAction = null, openPull = null, setTimer = setTimeout, clearTimer = clearTimeout, pollMs = 30000 }) {
|
||||
const prefix = 'stackchain.release-receipt.v1:';
|
||||
const limit = 12;
|
||||
let entries = [];
|
||||
let refreshing = null;
|
||||
const recoveries = new Map();
|
||||
const retrying = new Map();
|
||||
const rollingBack = new Map();
|
||||
let timer = null;
|
||||
let bound = false;
|
||||
documentRef ||= typeof document !== 'undefined' ? document : null;
|
||||
@@ -62,6 +65,17 @@ function createReleaseReceipt({ storage, getLogin, fetchJson, launcher = null, d
|
||||
number: Number(item.number),
|
||||
key: item.key || item.repository + '#' + item.number,
|
||||
commit_sha: commitSha,
|
||||
...(
|
||||
mergeResult?.source_repository === item.repository
|
||||
&& mergeResult?.source_branch
|
||||
&& mergeResult?.source_head_sha
|
||||
? {
|
||||
source_branch: String(mergeResult.source_branch),
|
||||
source_head_sha: String(mergeResult.source_head_sha),
|
||||
cleanup: { state: 'available', message: 'Merged branch retained.' },
|
||||
}
|
||||
: {}
|
||||
),
|
||||
status: null,
|
||||
captured_at: new Date().toISOString(),
|
||||
};
|
||||
@@ -81,10 +95,17 @@ function createReleaseReceipt({ storage, getLogin, fetchJson, launcher = null, d
|
||||
|
||||
function summarize(payload) {
|
||||
const checks = Array.isArray(payload?.checks) ? payload.checks : [];
|
||||
const failing = checks.filter(check => ['failure', 'error'].includes(check.state)).map(check => check.name).filter(Boolean);
|
||||
const failedChecks = checks.filter(check => ['failure', 'error'].includes(check.state));
|
||||
const failing = failedChecks.map(check => check.name).filter(Boolean);
|
||||
const failures = failedChecks.filter(check => check?.recovery).map(check => ({
|
||||
name: check.name || 'Failed check',
|
||||
description: check.description || '',
|
||||
url: check.url || '',
|
||||
recovery: check.recovery,
|
||||
}));
|
||||
const pending = checks.filter(check => check.state === 'pending').map(check => check.name).filter(Boolean);
|
||||
if (payload?.release) return { ...payload, label: 'Released · ' + payload.release.tag, checks: [] };
|
||||
if (failing.length) return { ...payload, label: 'Checks failed', checks: failing };
|
||||
if (failing.length) return { ...payload, label: 'Checks failed', checks: failing, failures };
|
||||
if (payload?.ci_state === 'success') return { ...payload, label: 'Checks passed · waiting for release', checks: [] };
|
||||
return { ...payload, label: 'Checks running', checks: pending };
|
||||
}
|
||||
@@ -121,18 +142,117 @@ function createReleaseReceipt({ storage, getLogin, fetchJson, launcher = null, d
|
||||
state.className = 'small';
|
||||
state.textContent = entry.status?.label || 'Checking the exact merge commit…';
|
||||
copy.append(title, state);
|
||||
if (entry.source_branch && entry.source_head_sha) {
|
||||
const branch = document.createElement('span');
|
||||
branch.className = 'small release-branch-cleanup-status';
|
||||
branch.textContent = entry.cleanup?.state === 'deleted'
|
||||
? 'Branch ' + entry.source_branch + ' · deleted'
|
||||
: 'Branch ' + entry.source_branch + ' · ' + entry.source_head_sha.slice(0, 8);
|
||||
copy.append(branch);
|
||||
}
|
||||
if (entry.rollback?.state === 'prepared') {
|
||||
const rollbackStatus = document.createElement('span');
|
||||
rollbackStatus.className = 'small release-rollback-status';
|
||||
rollbackStatus.textContent = entry.rollback.message;
|
||||
copy.append(rollbackStatus);
|
||||
}
|
||||
if (entry.status?.release?.url) {
|
||||
const link = document.createElement('a');
|
||||
link.href = entry.status.release.url;
|
||||
link.textContent = 'Open release ' + entry.status.release.tag;
|
||||
copy.append(link);
|
||||
}
|
||||
for (const failure of (entry.status?.failures || [])) {
|
||||
const runId = failure.recovery?.run_id;
|
||||
const jobIndex = failure.recovery?.job_index;
|
||||
if (!Number.isInteger(runId) || !Number.isInteger(jobIndex)) continue;
|
||||
const key = identity(entry) + '@' + runId + ':' + jobIndex;
|
||||
const summary = document.createElement('section');
|
||||
summary.className = 'release-failure-summary';
|
||||
const failureName = document.createElement('span');
|
||||
failureName.className = 'small';
|
||||
failureName.textContent = failure.name + (failure.description ? ' · ' + failure.description : '');
|
||||
const review = document.createElement('button');
|
||||
review.type = 'button';
|
||||
review.textContent = 'Review failure';
|
||||
review.setAttribute('aria-label', 'Review failed check ' + failure.name + ' for ' + entry.commit_sha.slice(0, 8));
|
||||
review.addEventListener('click', () => reviewFailure(
|
||||
entry.repository, entry.commit_sha, runId, jobIndex
|
||||
).catch(error => {
|
||||
if (statusNode) statusNode.textContent = String(error?.message || error) + ' Release evidence retained.';
|
||||
}));
|
||||
summary.append(failureName, review);
|
||||
const detail = recoveries.get(key);
|
||||
if (detail) {
|
||||
const recovery = document.createElement('div');
|
||||
recovery.className = 'release-failure-recovery';
|
||||
const sha = document.createElement('strong');
|
||||
sha.textContent = 'Merge ' + entry.commit_sha.slice(0, 8);
|
||||
const excerpt = document.createElement('pre');
|
||||
excerpt.textContent = detail.excerpt || 'No log excerpt was returned.';
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'release-failure-actions';
|
||||
if (failure.url) {
|
||||
const job = document.createElement('a');
|
||||
job.href = failure.url;
|
||||
job.textContent = 'Open job';
|
||||
actions.append(job);
|
||||
}
|
||||
const retry = document.createElement('button');
|
||||
retry.type = 'button';
|
||||
retry.textContent = retrying.has(key) ? 'Retrying…' : 'Retry failed check';
|
||||
retry.disabled = retrying.has(key);
|
||||
retry.addEventListener('click', () => retryFailure(
|
||||
entry.repository, entry.commit_sha, runId, jobIndex
|
||||
).catch(error => {
|
||||
if (statusNode) statusNode.textContent = String(error?.message || error) + ' Release evidence retained.';
|
||||
render();
|
||||
}));
|
||||
actions.append(retry);
|
||||
const rollback = document.createElement('button');
|
||||
rollback.type = 'button';
|
||||
rollback.textContent = entry.rollback?.state === 'prepared'
|
||||
? 'Open rollback #' + entry.rollback.number
|
||||
: (rollingBack.has(identity(entry)) ? 'Preparing rollback…' : 'Prepare rollback PR');
|
||||
rollback.disabled = rollingBack.has(identity(entry));
|
||||
rollback.setAttribute(
|
||||
'aria-label',
|
||||
'Prepare rollback pull request for ' + entry.key + ' at ' + entry.commit_sha.slice(0, 8),
|
||||
);
|
||||
rollback.addEventListener('click', () => prepareRollback(entry.repository, entry.commit_sha).catch(error => {
|
||||
if (statusNode) statusNode.textContent = String(error?.message || error) + ' Release evidence retained.';
|
||||
render();
|
||||
}));
|
||||
actions.append(rollback);
|
||||
recovery.append(sha, excerpt, actions);
|
||||
summary.append(recovery);
|
||||
}
|
||||
copy.append(summary);
|
||||
}
|
||||
const button = document.createElement('button');
|
||||
button.type = 'button';
|
||||
button.textContent = 'Dismiss';
|
||||
button.setAttribute('aria-label', 'Dismiss ' + entry.key + ' from release tracking');
|
||||
button.addEventListener('click', () => dismiss(entry.repository, entry.commit_sha));
|
||||
row.append(copy, button);
|
||||
if (entry.source_branch && entry.cleanup?.state !== 'deleted') {
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'release-watchlist-actions';
|
||||
const cleanup = document.createElement('button');
|
||||
cleanup.type = 'button';
|
||||
cleanup.textContent = entry.cleanup?.state === 'deleting' ? 'Deleting…' : 'Delete source branch';
|
||||
cleanup.disabled = entry.cleanup?.state === 'deleting' || entry.cleanup?.state === 'advanced';
|
||||
cleanup.setAttribute(
|
||||
'aria-label',
|
||||
'Delete merged source branch ' + entry.source_branch + ' at ' + entry.source_head_sha.slice(0, 8),
|
||||
);
|
||||
cleanup.addEventListener('click', () => deleteBranch(entry.repository, entry.commit_sha).catch(error => {
|
||||
if (statusNode) statusNode.textContent = String(error?.message || error);
|
||||
}));
|
||||
actions.append(cleanup, button);
|
||||
row.append(copy, actions);
|
||||
} else {
|
||||
row.append(copy, button);
|
||||
}
|
||||
return row;
|
||||
});
|
||||
listNode.replaceChildren(...rows);
|
||||
@@ -168,6 +288,149 @@ function createReleaseReceipt({ storage, getLogin, fetchJson, launcher = null, d
|
||||
finally { refreshing = null; }
|
||||
}
|
||||
|
||||
function recoveryPath(entry, runId, jobIndex) {
|
||||
return 'api/v1/repos/' + entry.repository.split('/').map(encodeURIComponent).join('/')
|
||||
+ '/pulls/' + encodeURIComponent(entry.number)
|
||||
+ '/release-receipt/' + encodeURIComponent(entry.commit_sha)
|
||||
+ '/checks/' + encodeURIComponent(runId) + '/jobs/' + encodeURIComponent(jobIndex);
|
||||
}
|
||||
|
||||
async function reviewFailure(repository, commitSha, runId, jobIndex) {
|
||||
const entry = entries.find(value => identity(value) === repository + '@' + commitSha);
|
||||
if (!entry) throw new Error('Tracked release is unavailable.');
|
||||
const key = identity(entry) + '@' + runId + ':' + jobIndex;
|
||||
const detail = await fetchJson(recoveryPath(entry, runId, jobIndex) + '/failure', {
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (detail?.commit_sha !== entry.commit_sha) {
|
||||
throw new Error('Release failure evidence did not match the merged commit.');
|
||||
}
|
||||
recoveries.set(key, detail);
|
||||
render();
|
||||
return detail;
|
||||
}
|
||||
|
||||
function retryFailure(repository, commitSha, runId, jobIndex) {
|
||||
const entry = entries.find(value => identity(value) === repository + '@' + commitSha);
|
||||
if (!entry) return Promise.reject(new Error('Tracked release is unavailable.'));
|
||||
const key = identity(entry) + '@' + runId + ':' + jobIndex;
|
||||
if (retrying.has(key)) return retrying.get(key);
|
||||
const approve = confirmAction || (windowRef?.confirm ? message => windowRef.confirm(message) : () => false);
|
||||
const failure = entry.status?.failures?.find(value =>
|
||||
value.recovery?.run_id === runId && value.recovery?.job_index === jobIndex
|
||||
);
|
||||
if (!approve('Retry ' + (failure?.name || 'failed release check') + ' for ' + commitSha.slice(0, 8) + '?')) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
const operation = fetchJson(recoveryPath(entry, runId, jobIndex) + '/retry', {
|
||||
method: 'POST',
|
||||
headers: { Accept: 'application/json' },
|
||||
}).then(result => {
|
||||
if (result?.commit_sha !== entry.commit_sha) {
|
||||
throw new Error('Release retry did not match the merged commit.');
|
||||
}
|
||||
entry.status = { ...entry.status, ci_state: 'pending', label: 'Checks running', checks: [], failures: [] };
|
||||
recoveries.delete(key);
|
||||
persist();
|
||||
render();
|
||||
schedule(0);
|
||||
return true;
|
||||
}).finally(() => retrying.delete(key));
|
||||
retrying.set(key, operation);
|
||||
return operation;
|
||||
}
|
||||
|
||||
function prepareRollback(repository, commitSha) {
|
||||
const entry = entries.find(value => identity(value) === repository + '@' + commitSha);
|
||||
if (!entry) return Promise.reject(new Error('Tracked release is unavailable.'));
|
||||
if (entry.rollback?.state === 'prepared') {
|
||||
openPull?.(entry.rollback.pull);
|
||||
return Promise.resolve(entry.rollback.pull);
|
||||
}
|
||||
const key = identity(entry);
|
||||
if (rollingBack.has(key)) return rollingBack.get(key);
|
||||
const approve = confirmAction || (windowRef?.confirm ? message => windowRef.confirm(message) : () => false);
|
||||
if (!approve('Prepare a draft rollback PR for ' + entry.key + ' at ' + commitSha.slice(0, 8) + '?')) {
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
const operation = fetchJson(
|
||||
'api/v1/repos/' + entry.repository.split('/').map(encodeURIComponent).join('/')
|
||||
+ '/pulls/' + encodeURIComponent(entry.number)
|
||||
+ '/release-receipt/' + encodeURIComponent(entry.commit_sha) + '/rollback',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Idempotency-Key': 'release-rollback-' + entry.number + '-' + entry.commit_sha,
|
||||
},
|
||||
},
|
||||
).then(result => {
|
||||
if (result?.rollback_of !== entry.commit_sha || !Number.isInteger(result?.number)) {
|
||||
throw new Error('Rollback preparation did not match the failed release.');
|
||||
}
|
||||
const pull = {
|
||||
...result,
|
||||
kind: 'pull',
|
||||
key: result.repository + '#' + result.number,
|
||||
state: 'open',
|
||||
};
|
||||
entry.rollback = {
|
||||
state: 'prepared',
|
||||
number: result.number,
|
||||
message: 'Draft rollback #' + result.number + ' is ready for review.',
|
||||
pull,
|
||||
};
|
||||
persist();
|
||||
render();
|
||||
if (dialog?.open) dialog.close();
|
||||
openPull?.(pull);
|
||||
return result;
|
||||
}).finally(() => rollingBack.delete(key));
|
||||
rollingBack.set(key, operation);
|
||||
render();
|
||||
return operation;
|
||||
}
|
||||
|
||||
async function deleteBranch(repository, commitSha) {
|
||||
const entry = entries.find(value => identity(value) === repository + '@' + commitSha);
|
||||
if (!entry?.source_branch || !entry?.source_head_sha || entry.cleanup?.state === 'deleted') {
|
||||
throw new Error('Source branch cleanup is unavailable.');
|
||||
}
|
||||
const approve = confirmAction || (windowRef?.confirm ? message => windowRef.confirm(message) : () => false);
|
||||
if (!approve('Delete ' + entry.source_branch + ' at ' + entry.source_head_sha.slice(0, 8) + '?')) return false;
|
||||
entry.cleanup = { state: 'deleting', message: 'Deleting source branch…' };
|
||||
persist();
|
||||
render();
|
||||
try {
|
||||
await fetchJson(
|
||||
'api/v1/repos/' + entry.repository.split('/').map(encodeURIComponent).join('/')
|
||||
+ '/pulls/' + encodeURIComponent(entry.number) + '/source-branch',
|
||||
{
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
||||
body: JSON.stringify({
|
||||
source_branch: entry.source_branch,
|
||||
expected_head_sha: entry.source_head_sha,
|
||||
}),
|
||||
},
|
||||
);
|
||||
entry.cleanup = { state: 'deleted', message: 'Source branch deleted.' };
|
||||
persist();
|
||||
render();
|
||||
return true;
|
||||
} catch (error) {
|
||||
entry.cleanup = {
|
||||
state: error?.status === 409 ? 'advanced' : 'available',
|
||||
message: error?.status === 409
|
||||
? 'Source branch has newer commits and was retained.'
|
||||
: 'Branch retained. Retry when connected.',
|
||||
};
|
||||
persist();
|
||||
render();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function dismiss(repository, commitSha) {
|
||||
if (repository && commitSha) entries = entries.filter(entry => identity(entry) !== repository + '@' + commitSha);
|
||||
else entries = [];
|
||||
@@ -195,7 +458,7 @@ function createReleaseReceipt({ storage, getLogin, fetchJson, launcher = null, d
|
||||
schedule();
|
||||
}
|
||||
|
||||
return { capture, restore, refresh, dismiss, bind, fetchJson };
|
||||
return { capture, restore, refresh, reviewFailure, retryFailure, prepareRollback, deleteBranch, dismiss, bind, fetchJson };
|
||||
}
|
||||
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = createReleaseReceipt;
|
||||
@@ -384,10 +384,20 @@ function renderChecks(checks, escapeHtml, { offline = false } = {}) {
|
||||
const url = typeof check.url === 'string' ? check.url : '';
|
||||
const link = url ? '<a class="ci-check-link" href="' + escapeHtml(url) +
|
||||
'" target="_blank" rel="noopener noreferrer">Open job</a>' : '';
|
||||
const recovery = check.recovery;
|
||||
const inspect = !offline && ['failure', 'error'].includes(check.state) &&
|
||||
Number.isInteger(recovery?.run_id) && recovery.run_id > 0 &&
|
||||
Number.isInteger(recovery?.job_index) && recovery.job_index >= 0
|
||||
? '<button type="button" class="ci-check-inspect" data-run-id="' + recovery.run_id +
|
||||
'" data-job-index="' + recovery.job_index + '">Inspect failure</button>'
|
||||
: '';
|
||||
const actions = inspect || link
|
||||
? '<div class="ci-check-actions">' + inspect + link + '</div>'
|
||||
: '';
|
||||
return '<article class="ci-check ci-check-' + escapeHtml(check.state || 'unknown') + '">' +
|
||||
'<div class="ci-check-copy"><strong>' + escapeHtml(check.name) + '</strong>' +
|
||||
'<span class="small">' + escapeHtml(check.state || 'unknown') +
|
||||
(check.description ? ' · ' + escapeHtml(check.description) : '') + '</span></div>' + link + '</article>';
|
||||
(check.description ? ' · ' + escapeHtml(check.description) : '') + '</span></div>' + actions + '</article>';
|
||||
}).join('');
|
||||
return { summary, html, expanded: failed > 0 };
|
||||
}
|
||||
|
||||
@@ -36,6 +36,16 @@
|
||||
};
|
||||
root.searchPreviewReplyPath = item => root.searchPreviewPath(item).replace(/\?.*$/, '') +
|
||||
'/comments?kind=' + encodeURIComponent(item.kind);
|
||||
root.searchPreviewMutation = fetchJson => (detail, action) => {
|
||||
if (action === 'reopen-pull') {
|
||||
const path = root.searchPreviewPath(detail).replace('/issues/', '/pulls/').replace(/\/preview.*$/, '/reopen');
|
||||
return fetchJson(path, {
|
||||
method:'PATCH', headers:{'Content-Type':'application/json'},
|
||||
body:JSON.stringify({expected_head_sha:detail.head_sha}),
|
||||
});
|
||||
}
|
||||
return fetchJson(root.searchPreviewPath(detail).replace(/\?.*$/, '') + '/' + action, {method:'PATCH'});
|
||||
};
|
||||
root.searchPreviewSubscriptionPath = item => root.searchPreviewPath(item).replace(/\?.*$/, '') +
|
||||
'/subscription?kind=' + encodeURIComponent(item.kind);
|
||||
root.searchPreviewSubscriptionOptions = fetchJson => {
|
||||
@@ -102,6 +112,30 @@
|
||||
(detail.watching ? 'Stop watching' : 'Watch ' + (detail.kind === 'pull' ? 'pull request' : 'issue'));
|
||||
button.disabled = state.status === 'watching' || state.status === 'unwatching';
|
||||
};
|
||||
root.renderSearchPreviewStart = (detail, state, button) => {
|
||||
const pull = detail.kind === 'pull' && detail.state === 'closed' &&
|
||||
detail.authored_pull_reopenable === true;
|
||||
const issue = detail.kind === 'issue' &&
|
||||
(detail.reopenable || (detail.state === 'open' && (detail.claimable || detail.assigned_to_me)));
|
||||
button.hidden = !(detail.reviewable || pull || issue);
|
||||
button.textContent = detail.reviewable ? 'Review now' : pull ? 'Reopen in My Work' :
|
||||
detail.reopenable ? 'Reopen & resume' :
|
||||
(detail.assigned_to_me ? 'Start in Today' : 'Assign & start');
|
||||
button.disabled = state.status === 'claiming' || state.status === 'reopening';
|
||||
};
|
||||
root.createSearchAuthoredPullRecovery = o =>
|
||||
async d => {
|
||||
if (!o.confirm('Reopen ' + d.repository + ' #' + d.number + '?')) return 'canceled';
|
||||
await o.reopen(d);
|
||||
await o.refresh();
|
||||
const item = o.find(d);
|
||||
if (!item) {
|
||||
o.unavailable('Reopened. Refresh My Work.');
|
||||
return 'unavailable';
|
||||
}
|
||||
o.open(item);
|
||||
return 'opened';
|
||||
};
|
||||
root.wireSearchPreviewWatch = (button, preview, getDetail) => button.addEventListener('click', () => {
|
||||
const detail = getDetail();
|
||||
if (detail) preview.setWatching(detail.watching !== true).catch(() => {});
|
||||
@@ -548,6 +582,9 @@
|
||||
reopen(detail) {
|
||||
return run('reopen', 'reopening', 'reopened', detail);
|
||||
},
|
||||
reopenPull(detail) {
|
||||
return run('reopen-pull', 'reopening', 'reopened', detail);
|
||||
},
|
||||
setWatching(watching) {
|
||||
if (watchRequest) return watchRequest;
|
||||
if (!current || typeof watch !== 'function') {
|
||||
|
||||
@@ -231,6 +231,8 @@
|
||||
passkey_counter_anomaly: 'Passkey counter anomaly',
|
||||
device_revoked: 'Device access revoked', all_sessions_revoked: 'All device access revoked',
|
||||
issue_closed: 'Issue closed', pull_merged: 'Pull request merged',
|
||||
source_branch_deleted: 'Source branch deleted',
|
||||
release_rollback_prepared: 'Release rollback prepared',
|
||||
comment_deleted: 'Comment deleted',
|
||||
pull_review_approved: 'Pull request approved',
|
||||
pull_review_changes_requested: 'Changes requested', gitea_time_logged: 'Gitea time logged',
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const BASE = new URL('./', self.location.href).pathname;
|
||||
importScripts(BASE + 'static/private-data-registry.js');
|
||||
importScripts(BASE + 'static/background-issue-sync.js');
|
||||
const CACHE = 'stackchain-dashboard-shell-v138';
|
||||
const CACHE = 'stackchain-dashboard-shell-v139';
|
||||
const OFFLINE_LEASE_URL = new URL(BASE + '__offline-session-lease', self.location.origin).href;
|
||||
const OUTAGE_STATUSES = new Set([500, 502, 503, 504]);
|
||||
const NAVIGATION_TIMEOUT_MS = self.__STACKCHAIN_NAVIGATION_TIMEOUT_MS || 4000;
|
||||
@@ -245,6 +245,7 @@ const SHELL = [
|
||||
BASE + 'static/voice-issue-capture.js',
|
||||
BASE + 'static/voice-conversation-capture.js',
|
||||
BASE + 'static/create-issue-sheet.js',
|
||||
BASE + 'static/create-pull-sheet.js',
|
||||
BASE + 'static/mobile-create-issue-nav.js',
|
||||
BASE + 'static/create-and-start.js',
|
||||
BASE + 'static/assign-and-start.js',
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
'use strict';
|
||||
|
||||
const repositoryPart = /^[A-Za-z0-9_.-]+$/;
|
||||
const queueFilters = ['today', 'agenda', 'attention', 'filed', 'update', 'later', 'draft', 'following'];
|
||||
const queueFilters = ['today', 'agenda', 'attention', 'filed', 'authored', 'update', 'later', 'draft', 'following'];
|
||||
const sections = {
|
||||
issue: ['overview', 'conversation', 'reply', 'actions'],
|
||||
filed: ['overview', 'conversation', 'reply', 'actions'],
|
||||
|
||||
+15
-4
@@ -32,6 +32,8 @@ class Session:
|
||||
csrf: str
|
||||
expires_at: int
|
||||
idle_expires_at: int | None = None
|
||||
principal_id: int | None = None
|
||||
principal_login: str | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -145,6 +147,8 @@ def issue_session(
|
||||
*,
|
||||
device_label: str = "This device",
|
||||
management_id: str | None = None,
|
||||
principal_id: int | None = None,
|
||||
principal_login: str | None = None,
|
||||
) -> tuple[str, Session]:
|
||||
issued_at = int(time.time() if now is None else now)
|
||||
ttl = int(os.getenv("STACKCHAIN_DASHBOARD_SESSION_TTL_SECONDS", str(DEFAULT_TTL_SECONDS)))
|
||||
@@ -165,6 +169,8 @@ def issue_session(
|
||||
session.expires_at,
|
||||
device_label=device_label,
|
||||
management_id=management_id,
|
||||
principal_id=principal_id,
|
||||
principal_login=principal_login,
|
||||
)
|
||||
return f"{encoded}.{signature}", session
|
||||
|
||||
@@ -211,6 +217,8 @@ def verify_session_with_reason(
|
||||
csrf=session.csrf,
|
||||
expires_at=session.expires_at,
|
||||
idle_expires_at=getattr(status, "idle_expires_at", None),
|
||||
principal_id=getattr(status, "principal_id", None),
|
||||
principal_login=getattr(status, "principal_login", None),
|
||||
)
|
||||
)
|
||||
|
||||
@@ -244,11 +252,14 @@ async def managed_session_active(management_id: str) -> bool:
|
||||
return status == "active"
|
||||
|
||||
|
||||
async def managed_session_statuses(management_ids) -> dict[str, str]:
|
||||
async def managed_session_statuses(
|
||||
management_ids, *, expected_principal_id: int | None = None
|
||||
) -> dict[str, str]:
|
||||
options = {"idle_timeout_seconds": idle_timeout_seconds()}
|
||||
if expected_principal_id is not None:
|
||||
options["expected_principal_id"] = expected_principal_id
|
||||
return await asyncio.to_thread(
|
||||
_session_store().managed_statuses,
|
||||
management_ids,
|
||||
idle_timeout_seconds=idle_timeout_seconds(),
|
||||
_session_store().managed_statuses, management_ids, **options
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ WORKER_RUNTIME_SOURCE = "static/background-issue-sync.js"
|
||||
FEATURE_SOURCES = {
|
||||
"comment-actions": ("static/comment-actions.js",),
|
||||
"issue-capture": (
|
||||
"static/voice-transcript-store.js", "static/voice-issue-capture.js", "static/create-issue-sheet.js", "static/mobile-create-issue-nav.js", "static/update-follow-up.js", "static/shared-image-capture.js",
|
||||
"static/voice-transcript-store.js", "static/voice-issue-capture.js", "static/create-issue-sheet.js", "static/create-pull-sheet.js", "static/mobile-create-issue-nav.js", "static/update-follow-up.js", "static/shared-image-capture.js",
|
||||
),
|
||||
"pull-workflow": ("static/pull-sheet.js", "static/review-sheet.js", "static/release-receipt.js"),
|
||||
"push-notifications": ("static/push-notifications.js",),
|
||||
|
||||
+1227
-30
File diff suppressed because it is too large.
Load diff
+881
-30
File diff suppressed because it is too large.
Load diff
@@ -8,7 +8,7 @@ API_MUTATION_BODY_LIMIT = 64 * 1024
|
||||
ISSUE_ATTACHMENT_BODY_LIMIT = 2 * 1024 * 1024 + 64 * 1024
|
||||
LEGACY_JSON_ATTACHMENT_BODY_LIMIT = 3 * 1024 * 1024
|
||||
UNFILED_DRAFT_SYNC_BODY_LIMIT = 17 * 1024 * 1024
|
||||
MUTATION_METHODS = frozenset({"POST", "PUT", "PATCH"})
|
||||
MUTATION_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})
|
||||
|
||||
|
||||
def request_body_limit(method: str, path: str) -> int | None:
|
||||
|
||||
+39
-9
@@ -18,10 +18,20 @@ class SessionStatus(str):
|
||||
"""String-compatible status carrying the server-confirmed idle deadline."""
|
||||
|
||||
idle_expires_at: int | None
|
||||
principal_id: int | None
|
||||
principal_login: str | None
|
||||
|
||||
def __new__(cls, value: str, idle_expires_at: int | None = None):
|
||||
def __new__(
|
||||
cls,
|
||||
value: str,
|
||||
idle_expires_at: int | None = None,
|
||||
principal_id: int | None = None,
|
||||
principal_login: str | None = None,
|
||||
):
|
||||
instance = super().__new__(cls, value)
|
||||
instance.idle_expires_at = idle_expires_at
|
||||
instance.principal_id = principal_id
|
||||
instance.principal_login = principal_login
|
||||
return instance
|
||||
|
||||
|
||||
@@ -71,7 +81,9 @@ class SessionStore:
|
||||
management_id TEXT,
|
||||
device_label TEXT,
|
||||
created_at INTEGER,
|
||||
last_active_at INTEGER
|
||||
last_active_at INTEGER,
|
||||
principal_id INTEGER,
|
||||
principal_login TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
@@ -98,6 +110,8 @@ class SessionStore:
|
||||
"device_label": "TEXT",
|
||||
"created_at": "INTEGER",
|
||||
"last_active_at": "INTEGER",
|
||||
"principal_id": "INTEGER",
|
||||
"principal_login": "TEXT",
|
||||
}
|
||||
for name, column_type in additions.items():
|
||||
if name not in columns:
|
||||
@@ -135,6 +149,8 @@ class SessionStore:
|
||||
*,
|
||||
device_label: str = "This device",
|
||||
management_id: str | None = None,
|
||||
principal_id: int | None = None,
|
||||
principal_login: str | None = None,
|
||||
) -> None:
|
||||
label = " ".join(str(device_label).split())[:64] or "This device"
|
||||
now = int(self.clock())
|
||||
@@ -145,8 +161,9 @@ class SessionStore:
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO active_sessions("
|
||||
"session_hash, expires_at, management_id, device_label, created_at, last_active_at"
|
||||
") VALUES (?, ?, ?, ?, ?, ?)",
|
||||
"session_hash, expires_at, management_id, device_label, created_at, last_active_at, "
|
||||
"principal_id, principal_login"
|
||||
") VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
(
|
||||
self._digest(session_id),
|
||||
expires_at,
|
||||
@@ -154,6 +171,8 @@ class SessionStore:
|
||||
label,
|
||||
now,
|
||||
now,
|
||||
principal_id,
|
||||
principal_login,
|
||||
),
|
||||
)
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
@@ -176,7 +195,8 @@ class SessionStore:
|
||||
) -> str:
|
||||
now = int(self.clock())
|
||||
query = (
|
||||
"SELECT expires_at, last_active_at FROM active_sessions "
|
||||
"SELECT expires_at, last_active_at, principal_id, principal_login "
|
||||
"FROM active_sessions "
|
||||
"WHERE session_hash = ?"
|
||||
)
|
||||
parameters = (self._digest(session_id),)
|
||||
@@ -185,7 +205,11 @@ class SessionStore:
|
||||
with self._connect() as connection:
|
||||
row = connection.execute(query, parameters).fetchone()
|
||||
except sqlite3.OperationalError as exc:
|
||||
if "no such column: last_active_at" not in str(exc):
|
||||
missing_migrated_column = any(
|
||||
f"no such column: {name}" in str(exc)
|
||||
for name in ("last_active_at", "principal_id", "principal_login")
|
||||
)
|
||||
if not missing_migrated_column:
|
||||
raise
|
||||
with self._connect(initialize=True) as connection:
|
||||
row = connection.execute(query, parameters).fetchone()
|
||||
@@ -196,7 +220,7 @@ class SessionStore:
|
||||
idle_expires_at = min(row[0], row[1] + max(1, idle_timeout_seconds))
|
||||
if idle_expires_at <= now:
|
||||
return SessionStatus("idle", idle_expires_at)
|
||||
return SessionStatus("active", idle_expires_at)
|
||||
return SessionStatus("active", idle_expires_at, row[2], row[3])
|
||||
|
||||
def touch(
|
||||
self, session_id: str, expires_at: int, *, idle_timeout_seconds: int
|
||||
@@ -279,7 +303,11 @@ class SessionStore:
|
||||
)[management_id]
|
||||
|
||||
def managed_statuses(
|
||||
self, management_ids, *, idle_timeout_seconds: int
|
||||
self,
|
||||
management_ids,
|
||||
*,
|
||||
idle_timeout_seconds: int,
|
||||
expected_principal_id: int | None = None,
|
||||
) -> dict[str, str]:
|
||||
"""Return authorization states for durable device identifiers in one read."""
|
||||
requested = set(management_ids)
|
||||
@@ -290,7 +318,7 @@ class SessionStore:
|
||||
with self._connect() as connection:
|
||||
placeholders = ",".join("?" for _ in requested)
|
||||
rows = connection.execute(
|
||||
"SELECT management_id, expires_at, last_active_at "
|
||||
"SELECT management_id, expires_at, last_active_at, principal_id "
|
||||
f"FROM active_sessions WHERE management_id IN ({placeholders})",
|
||||
tuple(requested),
|
||||
).fetchall()
|
||||
@@ -305,6 +333,8 @@ class SessionStore:
|
||||
statuses[management_id] = "revoked"
|
||||
elif row[1] + idle_timeout <= now:
|
||||
statuses[management_id] = "idle"
|
||||
elif expected_principal_id is not None and row[2] != expected_principal_id:
|
||||
statuses[management_id] = "principal_mismatch"
|
||||
else:
|
||||
statuses[management_id] = "active"
|
||||
return statuses
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_author_addresses_every_review_comment_and_requests_updated_review(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
detail = {
|
||||
"state": "open",
|
||||
"draft": False,
|
||||
"mergeable": True,
|
||||
"merged": False,
|
||||
"ci_state": "success",
|
||||
"head_sha": "current-head",
|
||||
"reviewers": [{
|
||||
"review_id": 42,
|
||||
"login": "sam",
|
||||
"status": "changes_requested",
|
||||
"head_sha": "current-head",
|
||||
"blocking": True,
|
||||
"comments": [
|
||||
{"id": 99, "path": "src/api.py", "body": "Handle the empty state.", "line": 12},
|
||||
{"id": 100, "path": "frontend/app.js", "body": "Explain the retry.", "line": 8},
|
||||
],
|
||||
}],
|
||||
"files": [
|
||||
{"filename": "src/api.py", "status": "modified", "diff_available": True,
|
||||
"diff_lines": ["@@ -11 +11 @@", "+return empty"]},
|
||||
{"filename": "frontend/app.js", "status": "modified", "diff_available": True,
|
||||
"diff_lines": ["@@ -7 +7 @@", "+showRetry()"]},
|
||||
],
|
||||
}
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""detail => {
|
||||
globalThis.confirm = () => true;
|
||||
globalThis.feedbackCalls = [];
|
||||
globalThis.feedbackStored = new Map();
|
||||
globalThis.feedbackStorage = {
|
||||
getItem:key => feedbackStored.has(key) ? feedbackStored.get(key) : null,
|
||||
setItem:(key, value) => feedbackStored.set(key, String(value)),
|
||||
removeItem:key => feedbackStored.delete(key),
|
||||
};
|
||||
globalThis.feedbackItem = {repository:'stackchain/api', number:7, key:'stackchain/api#7'};
|
||||
globalThis.feedbackDetail = detail;
|
||||
globalThis.feedbackController = createPullSheet({
|
||||
storage: feedbackStorage,
|
||||
createOperationId: () => 'feedback-operation',
|
||||
fetchJson: async (path, options = {}) => {
|
||||
feedbackCalls.push({path, options});
|
||||
if (path.endsWith('/comments')) return {id: 501, body:JSON.parse(options.body).body};
|
||||
if (path.endsWith('/request-review')) return {
|
||||
number:7, reviewer:'sam', head_sha:'current-head', requested_reviewers:['sam']
|
||||
};
|
||||
throw new Error('unexpected request');
|
||||
},
|
||||
});
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
document.querySelector('#pull-review').open = true;
|
||||
document.querySelector('#pull-files').innerHTML = detail.files.map((file, index) =>
|
||||
createPullSheet.renderFile(file, index, false, value => String(value)
|
||||
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'))
|
||||
).join('');
|
||||
createPullSheet.bindFeedbackControls(document, feedbackController,
|
||||
() => feedbackItem, () => feedbackDetail, () => 'timmy');
|
||||
createPullSheet.review(detail, null, document);
|
||||
}""",
|
||||
detail,
|
||||
)
|
||||
|
||||
page.locator(".pull-review-feedback summary").click()
|
||||
page.locator('[data-address-review-feedback="42"]').click()
|
||||
assert page.locator("#pull-feedback-progress").text_content() == "Comment 1 of 2"
|
||||
assert page.locator("#finish-pull-feedback").is_disabled()
|
||||
page.locator('[data-feedback-disposition="addressed"]').click()
|
||||
page.locator("#next-pull-feedback").click()
|
||||
page.locator("#pull-feedback-note").fill("Added a visible retry message.")
|
||||
page.locator('[data-feedback-disposition="discussion"]').click()
|
||||
assert not page.locator("#finish-pull-feedback").is_disabled()
|
||||
page.locator("#finish-pull-feedback").click()
|
||||
page.locator("#request-feedback-review").click()
|
||||
|
||||
page.wait_for_function("feedbackCalls.length === 2")
|
||||
result = page.evaluate(
|
||||
"""() => ({
|
||||
calls:feedbackCalls,
|
||||
scrollWidth:document.documentElement.scrollWidth,
|
||||
clientWidth:document.documentElement.clientWidth,
|
||||
controlHeights:Array.from(document.querySelectorAll('#pull-feedback-pass button'))
|
||||
.filter(button => !button.hidden).map(button => button.getBoundingClientRect().height),
|
||||
status:document.querySelector('#pull-feedback-status').textContent,
|
||||
secondExpanded:document.querySelector('[data-pull-filename="frontend/app.js"] .pull-file-toggle')
|
||||
.getAttribute('aria-expanded'),
|
||||
persisted:Array.from(feedbackStored.keys()).some(key => key.includes('feedback-pass')),
|
||||
})"""
|
||||
)
|
||||
result["resetHidden"] = page.evaluate(
|
||||
"""() => {
|
||||
createPullSheet.resetReviewRequestControls(document, feedbackDetail);
|
||||
return document.querySelector('#pull-feedback-pass').hidden;
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
|
||||
assert result["scrollWidth"] <= result["clientWidth"]
|
||||
assert min(result["controlHeights"]) >= 44
|
||||
assert result["secondExpanded"] == "true"
|
||||
assert result["persisted"] is True
|
||||
assert result["resetHidden"] is True
|
||||
assert result["calls"][0]["path"].endswith("/comments")
|
||||
assert result["calls"][0]["options"]["headers"]["Idempotency-Key"] == "feedback-operation"
|
||||
summary = result["calls"][0]["options"]["body"]
|
||||
assert "Handle the empty state" in summary
|
||||
assert "Addressed" in summary
|
||||
assert "Needs discussion" in summary
|
||||
assert "Added a visible retry message" in summary
|
||||
assert result["calls"][1]["path"].endswith("/request-review")
|
||||
assert '"reviewer":"sam"' in result["calls"][1]["options"]["body"]
|
||||
assert result["status"] == "Response posted; updated review requested from @sam."
|
||||
@@ -0,0 +1,85 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_author_commits_one_review_feedback_fix(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
detail = {
|
||||
"state": "open", "merged": False, "head_sha": "abc1234",
|
||||
"capabilities": {"authored": True},
|
||||
"reviewers": [{
|
||||
"review_id": 42, "login": "sam", "status": "changes_requested",
|
||||
"head_sha": "abc1234", "blocking": True, "feedback_state": "loaded",
|
||||
"comments": [{"id": 99, "path": "src/api.py", "body": "Handle empty state.", "line": 12}],
|
||||
}],
|
||||
"files": [{"filename": "src/api.py", "status": "modified", "diff_available": True,
|
||||
"diff_lines": ["@@ -12 +12 @@", "+return empty"]}],
|
||||
}
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""detail => {
|
||||
globalThis.confirm = () => true;
|
||||
globalThis.fixCalls = [];
|
||||
globalThis.fixItem = {repository:'stackchain/api', number:7, key:'stackchain/api#7'};
|
||||
globalThis.fixDetail = detail;
|
||||
globalThis.fixController = createPullSheet({fetchJson: async (path, options = {}) => {
|
||||
fixCalls.push({path, options});
|
||||
if ((options.method || 'GET') === 'GET') return {
|
||||
path:'src/api.py', head_sha:'abc1234', blob_sha:'blob123', content:'return empty\\n'
|
||||
};
|
||||
return {path:'src/api.py', previous_head_sha:'abc1234', head_sha:'def5678', blob_sha:'blob456'};
|
||||
}});
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
document.querySelector('#pull-review').open = true;
|
||||
document.querySelector('#pull-files').innerHTML = detail.files.map((file, index) =>
|
||||
createPullSheet.renderFile(file, index, false, value => String(value))
|
||||
).join('');
|
||||
createPullSheet.bindFeedbackControls(document, fixController,
|
||||
() => fixItem, () => fixDetail, () => 'alex');
|
||||
createPullSheet.review(detail, null, document);
|
||||
}""",
|
||||
detail,
|
||||
)
|
||||
|
||||
page.locator(".pull-review-feedback summary").click()
|
||||
page.locator('[data-address-review-feedback="42"]').click()
|
||||
page.locator("#make-pull-feedback-fix").click()
|
||||
page.locator("#pull-feedback-file-content").fill("return handled\n")
|
||||
page.locator("#pull-feedback-commit-message").fill("fix: handle empty state")
|
||||
page.locator("#commit-pull-feedback-fix").click()
|
||||
page.wait_for_function("fixCalls.length === 2")
|
||||
result = page.evaluate("""() => ({
|
||||
calls:fixCalls, head:fixDetail.head_sha,
|
||||
editorHidden:document.querySelector('#pull-feedback-file-editor').hidden,
|
||||
status:document.querySelector('#pull-feedback-status').textContent,
|
||||
scrollWidth:document.documentElement.scrollWidth,
|
||||
clientWidth:document.documentElement.clientWidth,
|
||||
heights:Array.from(document.querySelectorAll('#pull-feedback-pass button'))
|
||||
.filter(button => button.getClientRects().length > 0).map(button => button.getBoundingClientRect().height),
|
||||
})""")
|
||||
browser.close()
|
||||
|
||||
assert result["scrollWidth"] <= result["clientWidth"]
|
||||
assert min(result["heights"]) >= 44
|
||||
assert result["head"] == "def5678"
|
||||
assert result["editorHidden"] is True
|
||||
assert "committed" in result["status"].lower()
|
||||
assert "path=src%2Fapi.py" in result["calls"][0]["path"]
|
||||
body = result["calls"][1]["options"]["body"]
|
||||
assert '"expected_blob_sha":"blob123"' in body
|
||||
assert '"content":"return handled\\n"' in body
|
||||
@@ -0,0 +1,109 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
|
||||
pytest.skip("packaged mobile My PRs journey runs only in its gated CI job", allow_module_level=True)
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
FRONTEND = ROOT / "frontend"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [
|
||||
{"width": 320, "height": 568},
|
||||
{"width": 390, "height": 844},
|
||||
])
|
||||
def test_authored_pull_queue_is_phone_usable_and_opens_the_existing_pull_route(viewport):
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport=viewport)
|
||||
page.set_content((FRONTEND / "index.html").read_text())
|
||||
page.add_style_tag(path=FRONTEND / "dashboard.css")
|
||||
page.add_script_tag(path=FRONTEND / "my-work.js")
|
||||
page.add_script_tag(path=FRONTEND / "work-route.js")
|
||||
page.add_script_tag(path=FRONTEND / "mobile-queue-launcher.js")
|
||||
page.add_script_tag(path=FRONTEND / "pull-sheet.js")
|
||||
page.evaluate("document.querySelector('#mobile-queue-sheet').showModal()")
|
||||
|
||||
row = page.locator('[data-mobile-queue="authored"]')
|
||||
expect(row).to_have_count(1)
|
||||
expect(row).to_contain_text("My PRs")
|
||||
expect(row).to_contain_text("Pull requests you authored")
|
||||
assert row.bounding_box()["height"] >= 44
|
||||
|
||||
result = page.evaluate("""() => {
|
||||
const work = buildMyWork({
|
||||
user:{login:'timmy'},
|
||||
pull_requests:[{
|
||||
number:41,title:'Ship the authored mobile flow',repository:'stackchain/dashboard',
|
||||
state:'open',user:'timmy',assignees:[],work_reasons:['authored_by_me'],
|
||||
url:'https://forge.example/git/stackchain/dashboard/pulls/41'
|
||||
}]
|
||||
});
|
||||
const authored = filterMyWork(work, 'authored');
|
||||
let selected = '';
|
||||
let route = '';
|
||||
const action = document.createElement('button');
|
||||
action.className = 'my-work-card-main';
|
||||
action.addEventListener('click', () => { route = createWorkRoute.serialize(authored[0]); });
|
||||
const launcher = createMobileQueueLauncher({
|
||||
selectFilter:name => { selected = name; },
|
||||
firstAction:() => action,
|
||||
announce:() => {},
|
||||
});
|
||||
const opened = launcher.open('authored');
|
||||
return {selected, route, opened, count:authored.length};
|
||||
}""")
|
||||
assert result == {
|
||||
"selected": "authored",
|
||||
"route": "#/my-work/pull/stackchain/dashboard/41",
|
||||
"opened": "opened",
|
||||
"count": 1,
|
||||
}
|
||||
capabilities = page.evaluate("""() => {
|
||||
const item = {key:'stackchain/dashboard#41'};
|
||||
createPullSheet.resetOwnershipControls(
|
||||
document, item, () => false, {authored:true, assigned:false}
|
||||
);
|
||||
const ownership = document.querySelector('#pull-ownership');
|
||||
return {
|
||||
hidden: ownership.hidden,
|
||||
inert: ownership.inert,
|
||||
releaseDisabled: document.querySelector('#release-pull').disabled,
|
||||
handoffDisabled: document.querySelector('#load-pull-handoff').disabled,
|
||||
};
|
||||
}""")
|
||||
assert capabilities == {
|
||||
"hidden": True,
|
||||
"inert": True,
|
||||
"releaseDisabled": True,
|
||||
"handoffDisabled": True,
|
||||
}
|
||||
assert page.evaluate(
|
||||
"document.documentElement.scrollWidth > document.documentElement.clientWidth"
|
||||
) is False
|
||||
browser.close()
|
||||
|
||||
|
||||
def test_empty_authored_queue_announces_the_standard_empty_message():
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport={"width": 320, "height": 568})
|
||||
page.set_content((FRONTEND / "index.html").read_text())
|
||||
page.add_script_tag(path=FRONTEND / "mobile-queue-launcher.js")
|
||||
|
||||
message = page.evaluate("""() => {
|
||||
let announcement = '';
|
||||
const launcher = createMobileQueueLauncher({
|
||||
selectFilter:() => {}, firstAction:() => null,
|
||||
announce:value => { announcement = value; },
|
||||
});
|
||||
launcher.open('authored');
|
||||
return announcement;
|
||||
}""")
|
||||
assert message == "No work is ready to open."
|
||||
browser.close()
|
||||
@@ -0,0 +1,88 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
|
||||
if os.environ.get("STACKCHAIN_RUN_RELEASE_E2E") != "1":
|
||||
pytest.skip("release browser journey is opt-in", allow_module_level=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_author_cancels_pending_review_and_opens_replacement_picker(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
globalThis.confirm = () => true;
|
||||
globalThis.cancelCalls = [];
|
||||
globalThis.cancelItem = {
|
||||
repository:'stackchain/api', number:7, key:'stackchain/api#7'
|
||||
};
|
||||
globalThis.cancelDetail = {
|
||||
state:'open', draft:false, mergeable:true, merged:false,
|
||||
ci_state:'success', head_sha:'abc1234', files:[],
|
||||
reviewers:[{
|
||||
login:'sam', status:'waiting', head_sha:'abc1234', blocking:true
|
||||
}],
|
||||
};
|
||||
globalThis.cancelController = createPullSheet({
|
||||
storage:null,
|
||||
fetchJson:async (path, options={}) => {
|
||||
cancelCalls.push({path, options});
|
||||
return {
|
||||
repository:'stackchain/api', number:7, reviewer:'sam',
|
||||
head_sha:'abc1234', requested_reviewers:[],
|
||||
};
|
||||
},
|
||||
});
|
||||
createPullSheet.bindReviewRequestControls(
|
||||
document, cancelController, () => cancelItem, () => cancelDetail
|
||||
);
|
||||
createPullSheet.review(cancelDetail, null, document);
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
document.querySelector('#pull-review').open = true;
|
||||
}"""
|
||||
)
|
||||
|
||||
cancel = page.locator('[data-cancel-review-request="sam"]')
|
||||
bounds = cancel.bounding_box()
|
||||
assert bounds and bounds["height"] >= 44
|
||||
cancel.click()
|
||||
page.wait_for_function("cancelCalls.length === 1")
|
||||
page.wait_for_function(
|
||||
"document.querySelector('#pull-review-request-status').textContent.includes('Choose a replacement reviewer')"
|
||||
)
|
||||
result = page.evaluate(
|
||||
"""() => ({
|
||||
calls:cancelCalls,
|
||||
waitingRows:document.querySelectorAll('[data-reviewer-status="waiting"]').length,
|
||||
pickerOpen:document.querySelector('#pull-review-request').open,
|
||||
focused:document.activeElement?.id,
|
||||
scrollWidth:document.documentElement.scrollWidth,
|
||||
clientWidth:document.documentElement.clientWidth,
|
||||
})"""
|
||||
)
|
||||
browser.close()
|
||||
|
||||
assert result["scrollWidth"] <= result["clientWidth"]
|
||||
assert result["waitingRows"] == 0
|
||||
assert result["pickerOpen"] is True
|
||||
assert result["focused"] == "load-pull-reviewers"
|
||||
assert len(result["calls"]) == 1
|
||||
assert result["calls"][0]["options"]["method"] == "DELETE"
|
||||
assert result["calls"][0]["options"]["body"] == (
|
||||
'{"reviewer":"sam","expected_head_sha":"abc1234"}'
|
||||
)
|
||||
@@ -0,0 +1,87 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("STACKCHAIN_RUN_RELEASE_E2E") != "1",
|
||||
reason="release browser journey is opt-in",
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_author_closes_obsolete_pull_then_recovers_it(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.on("dialog", lambda dialog: dialog.accept())
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""() => {
|
||||
window.lifecycleCalls = [];
|
||||
window.lifecycleItem = {repository:'stackchain/api', number:7, key:'stackchain/api#7'};
|
||||
window.lifecycleDetail = {
|
||||
number:7, title:'Obsolete experiment', author:'timmy', state:'open',
|
||||
merged:false, head_sha:'abc1234', capabilities:{authored:true, assigned:false},
|
||||
};
|
||||
const controller = createPullSheet({
|
||||
storage:null,
|
||||
fetchJson:async (path, options) => {
|
||||
lifecycleCalls.push({path, method:options.method, body:JSON.parse(options.body)});
|
||||
const state = path.endsWith('/close') ? 'closed' : 'open';
|
||||
return {repository:'stackchain/api', number:7, title:'Obsolete experiment',
|
||||
head_sha:'abc1234', state, merged:false};
|
||||
},
|
||||
});
|
||||
createPullSheet.bindLifecycleControls(
|
||||
document, controller, () => lifecycleItem, () => lifecycleDetail,
|
||||
result => { lifecycleDetail = {...lifecycleDetail, ...result}; }
|
||||
);
|
||||
createPullSheet.resetLifecycleControls(document, lifecycleDetail);
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
}"""
|
||||
)
|
||||
|
||||
page.locator("#pull-lifecycle summary").click()
|
||||
close = page.get_by_role("button", name="Close pull request")
|
||||
before = close.evaluate("button => ({height:button.getBoundingClientRect().height, hidden:button.hidden})")
|
||||
close.click()
|
||||
page.get_by_text("Pull request closed.").wait_for()
|
||||
reopen = page.get_by_role("button", name="Reopen pull request")
|
||||
receipt = reopen.evaluate("button => ({height:button.getBoundingClientRect().height, hidden:button.closest('[hidden]') !== null})")
|
||||
reopen.click()
|
||||
page.get_by_text("Pull request reopened.").wait_for()
|
||||
metrics = page.evaluate(
|
||||
"""() => ({
|
||||
calls:lifecycleCalls,
|
||||
state:lifecycleDetail.state,
|
||||
closeHidden:document.querySelector('#close-authored-pull').hidden,
|
||||
receiptHidden:document.querySelector('#pull-close-receipt').hidden,
|
||||
focused:document.activeElement === document.querySelector('#close-authored-pull'),
|
||||
scrollWidth:document.documentElement.scrollWidth,
|
||||
clientWidth:document.documentElement.clientWidth,
|
||||
})"""
|
||||
)
|
||||
browser.close()
|
||||
|
||||
assert before["hidden"] is False
|
||||
assert before["height"] >= 44
|
||||
assert receipt["height"] >= 44
|
||||
assert receipt["hidden"] is False
|
||||
assert [call["path"].rsplit("/", 1)[-1] for call in metrics["calls"]] == ["close", "reopen"]
|
||||
assert all(call["body"] == {"expected_head_sha": "abc1234"} for call in metrics["calls"])
|
||||
assert metrics["state"] == "open"
|
||||
assert metrics["closeHidden"] is False
|
||||
assert metrics["receiptHidden"] is True
|
||||
assert metrics["focused"] is True
|
||||
assert metrics["scrollWidth"] <= metrics["clientWidth"]
|
||||
@@ -0,0 +1,87 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_author_publishes_draft_and_continues_to_reviewer_picker(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
detail = {
|
||||
"number": 7,
|
||||
"title": "WIP: Ship mobile flow",
|
||||
"author": "timmy",
|
||||
"state": "open",
|
||||
"draft": True,
|
||||
"merged": False,
|
||||
"head_sha": "abc1234",
|
||||
}
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.on("dialog", lambda dialog: dialog.accept())
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""detail => {
|
||||
window.publishDetail = detail;
|
||||
window.publishItem = {repository:'stackchain/api', number:7, key:'stackchain/api#7'};
|
||||
const controller = createPullSheet({
|
||||
storage:null,
|
||||
fetchJson:(path, options) => {
|
||||
if (!path.endsWith('/ready') || options.method !== 'PATCH') {
|
||||
return Promise.reject(new Error('unexpected request'));
|
||||
}
|
||||
const payload = JSON.parse(options.body);
|
||||
if (payload.expected_head_sha !== detail.head_sha) {
|
||||
return Promise.reject(new Error('wrong head'));
|
||||
}
|
||||
return Promise.resolve({
|
||||
repository:'stackchain/api', number:7, title:'Ship mobile flow',
|
||||
head_sha:detail.head_sha, state:'open', draft:false,
|
||||
});
|
||||
},
|
||||
});
|
||||
createPullSheet.bindOwnershipControls(
|
||||
document, controller, () => window.publishItem, async () => false,
|
||||
() => window.publishDetail, () => 'timmy'
|
||||
);
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
controller.setReviewDetail(detail);
|
||||
}""",
|
||||
detail,
|
||||
)
|
||||
|
||||
ready = page.get_by_role("button", name="Ready for review")
|
||||
before = ready.evaluate("button => ({height:button.getBoundingClientRect().height, hidden:button.hidden})")
|
||||
ready.click()
|
||||
page.get_by_text("Published and ready for review.").wait_for()
|
||||
metrics = page.evaluate(
|
||||
"""() => ({
|
||||
scrollWidth:document.documentElement.scrollWidth,
|
||||
clientWidth:document.documentElement.clientWidth,
|
||||
readyHidden:document.querySelector('#publish-draft-pull').hidden,
|
||||
requestOpen:document.querySelector('#pull-review-request').open,
|
||||
reviewerFocused:document.activeElement === document.querySelector('#load-pull-reviewers'),
|
||||
title:window.publishDetail.title,
|
||||
draft:window.publishDetail.draft,
|
||||
})"""
|
||||
)
|
||||
browser.close()
|
||||
|
||||
assert before["hidden"] is False
|
||||
assert before["height"] >= 44
|
||||
assert metrics["scrollWidth"] <= metrics["clientWidth"]
|
||||
assert metrics["readyHidden"] is True
|
||||
assert metrics["requestOpen"] is True
|
||||
assert metrics["reviewerFocused"] is True
|
||||
assert metrics["title"] == "Ship mobile flow"
|
||||
assert metrics["draft"] is False
|
||||
@@ -0,0 +1,172 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_received_review_feedback_opens_matching_change(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
detail = {
|
||||
"state": "open",
|
||||
"draft": False,
|
||||
"mergeable": True,
|
||||
"merged": False,
|
||||
"ci_state": "success",
|
||||
"head_sha": "current-head",
|
||||
"reviewers": [{
|
||||
"login": "sam",
|
||||
"status": "outdated",
|
||||
"head_sha": "old-head-123456",
|
||||
"blocking": True,
|
||||
"summary": "Please handle the narrow empty state before merging.",
|
||||
"comments": [{
|
||||
"path": "src/a/very/long/mobile/path/review_target.py",
|
||||
"body": "Return before parsing when the payload is empty.",
|
||||
"line": 12,
|
||||
}],
|
||||
}],
|
||||
"files": [{
|
||||
"filename": "src/a/very/long/mobile/path/review_target.py",
|
||||
"status": "modified",
|
||||
"additions": 2,
|
||||
"deletions": 1,
|
||||
"diff_available": True,
|
||||
"diff_lines": ["@@ -10,2 +10,3 @@", "-parse(payload)", "+if not payload: return", "+parse(payload)"],
|
||||
}],
|
||||
}
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""detail => {
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
document.querySelector('#pull-review').open = true;
|
||||
createPullSheet.review(detail, null, document);
|
||||
document.querySelector('#pull-files').innerHTML = detail.files.map((file, index) =>
|
||||
createPullSheet.renderFile(file, index, false, value => String(value)
|
||||
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'))
|
||||
).join('');
|
||||
}""",
|
||||
detail,
|
||||
)
|
||||
|
||||
page.locator(".pull-review-feedback summary").click()
|
||||
jump = page.locator('[data-review-feedback-file]')
|
||||
jump.click()
|
||||
metrics = page.evaluate(
|
||||
"""() => {
|
||||
const jump = document.querySelector('[data-review-feedback-file]');
|
||||
const toggle = document.querySelector('.pull-file-toggle');
|
||||
const panel = document.getElementById(toggle.getAttribute('aria-controls'));
|
||||
return {
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
jumpHeight: jump.getBoundingClientRect().height,
|
||||
expanded: toggle.getAttribute('aria-expanded'),
|
||||
panelHidden: panel.hidden,
|
||||
focused: document.activeElement === toggle,
|
||||
reviewedHead: document.querySelector('.pull-review-feedback').textContent,
|
||||
updatedReviewVisible: !document.querySelector('#request-updated-pull-review').hidden,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
|
||||
assert metrics["scrollWidth"] <= metrics["clientWidth"]
|
||||
assert metrics["jumpHeight"] >= 44
|
||||
assert metrics["expanded"] == "true"
|
||||
assert metrics["panelHidden"] is False
|
||||
assert metrics["focused"] is True
|
||||
assert "Reviewed head old-head" in metrics["reviewedHead"]
|
||||
assert metrics["updatedReviewVisible"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_pull_review_retries_inline_feedback_without_losing_core_review(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
detail = {
|
||||
"state": "open", "draft": False, "mergeable": True, "merged": False,
|
||||
"ci_state": "success", "head_sha": "abc1234",
|
||||
"reviewers": [{
|
||||
"login": "sam", "review_id": 8, "status": "changes_requested",
|
||||
"head_sha": "abc1234", "blocking": True,
|
||||
"summary": "Please handle the empty state.",
|
||||
}],
|
||||
"files": [],
|
||||
}
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""detail => {
|
||||
window.lazyFeedbackDetail = detail;
|
||||
window.lazyFeedbackItem = {repository:'stackchain/api', number:7, key:'stackchain/api#7'};
|
||||
let attempts = 0;
|
||||
const controller = createPullSheet({
|
||||
storage:null,
|
||||
fetchJson:() => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) return Promise.reject(new Error('feedback unavailable'));
|
||||
return Promise.resolve({
|
||||
review_id:8, head_sha:'abc1234', reviewed_head_sha:'abc1234',
|
||||
comments:[{id:99, path:'src/api.py', body:'Return before parsing.', line:12}],
|
||||
});
|
||||
},
|
||||
});
|
||||
createPullSheet.bindFeedbackControls(
|
||||
document, controller, () => window.lazyFeedbackItem,
|
||||
() => window.lazyFeedbackDetail, () => 'timmy'
|
||||
);
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
document.querySelector('#pull-review').open = true;
|
||||
const eligibility = createPullSheet.review(detail, null, document);
|
||||
document.querySelector('#pull-merge-state').textContent = eligibility.reason;
|
||||
}""",
|
||||
detail,
|
||||
)
|
||||
|
||||
page.locator(".pull-review-feedback summary").click()
|
||||
load = page.get_by_role("button", name="Load inline feedback")
|
||||
load.click()
|
||||
retry = page.get_by_role("button", name="Retry feedback")
|
||||
retry.wait_for()
|
||||
retry.click()
|
||||
page.get_by_text("Return before parsing.").wait_for()
|
||||
metrics = page.evaluate(
|
||||
"""() => {
|
||||
const details = document.querySelector('.pull-review-feedback');
|
||||
const address = document.querySelector('[data-address-review-feedback]');
|
||||
return {
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
blocker: document.querySelector('#pull-merge-state').textContent,
|
||||
feedback: details.textContent,
|
||||
addressHeight: address.getBoundingClientRect().height,
|
||||
};
|
||||
}"""
|
||||
)
|
||||
browser.close()
|
||||
|
||||
assert metrics["scrollWidth"] <= metrics["clientWidth"]
|
||||
assert "requested changes" in metrics["blocker"]
|
||||
assert "Return before parsing." in metrics["feedback"]
|
||||
assert metrics["addressHeight"] >= 44
|
||||
@@ -0,0 +1,87 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [(320, 568), (390, 844)])
|
||||
def test_mobile_pull_reviewer_status_wraps_and_keeps_updated_review_reachable(viewport):
|
||||
playwright = pytest.importorskip("playwright.sync_api")
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
detail = {
|
||||
"state": "open",
|
||||
"draft": False,
|
||||
"mergeable": True,
|
||||
"merged": False,
|
||||
"ci_state": "success",
|
||||
"head_sha": "current-head",
|
||||
"reviewers": [
|
||||
{
|
||||
"login": "casey-with-a-very-long-mobile-login",
|
||||
"status": "waiting",
|
||||
"head_sha": "current-head",
|
||||
"blocking": True,
|
||||
},
|
||||
{
|
||||
"login": "sam",
|
||||
"status": "changes_requested",
|
||||
"head_sha": "current-head",
|
||||
"blocking": True,
|
||||
},
|
||||
{
|
||||
"login": "lee",
|
||||
"status": "outdated",
|
||||
"head_sha": "old-head",
|
||||
"blocking": True,
|
||||
},
|
||||
{
|
||||
"login": "pat",
|
||||
"status": "approved",
|
||||
"head_sha": "current-head",
|
||||
"blocking": False,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
with playwright.sync_playwright() as runtime:
|
||||
try:
|
||||
browser = runtime.chromium.launch(headless=True)
|
||||
except Exception as error:
|
||||
pytest.skip(f"Chromium is not installed: {error}")
|
||||
page = browser.new_page(viewport={"width": viewport[0], "height": viewport[1]})
|
||||
page.set_content(html, wait_until="domcontentloaded")
|
||||
page.add_style_tag(path=ROOT / "frontend" / "dashboard.css")
|
||||
page.add_script_tag(path=ROOT / "frontend" / "pull-sheet.js")
|
||||
page.evaluate(
|
||||
"""detail => {
|
||||
document.querySelector('#pull-sheet').classList.add('open');
|
||||
document.querySelector('#pull-review').open = true;
|
||||
createPullSheet.review(detail, null, document);
|
||||
}""",
|
||||
detail,
|
||||
)
|
||||
|
||||
metrics = page.evaluate(
|
||||
"""() => ({
|
||||
scrollWidth: document.documentElement.scrollWidth,
|
||||
clientWidth: document.documentElement.clientWidth,
|
||||
updatedReviewHeight: document.querySelector('#request-updated-pull-review')
|
||||
.getBoundingClientRect().height,
|
||||
updatedReviewVisible: !document.querySelector('#request-updated-pull-review').hidden,
|
||||
statuses: Array.from(document.querySelectorAll('.pull-reviewer-status span'))
|
||||
.map(node => node.textContent),
|
||||
})"""
|
||||
)
|
||||
browser.close()
|
||||
|
||||
assert metrics["scrollWidth"] <= metrics["clientWidth"]
|
||||
assert metrics["updatedReviewHeight"] >= 44
|
||||
assert metrics["updatedReviewVisible"] is True
|
||||
assert metrics["statuses"] == [
|
||||
"Waiting for review",
|
||||
"Changes requested",
|
||||
"Outdated after new commits",
|
||||
"Approved current head",
|
||||
]
|
||||
@@ -0,0 +1,135 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
|
||||
pytest.skip("packaged release-failure recovery runs only in the browser gate", allow_module_level=True)
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
FRONTEND = ROOT / "frontend"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [
|
||||
{"width": 320, "height": 568},
|
||||
{"width": 390, "height": 844},
|
||||
])
|
||||
def test_failed_release_check_is_diagnosable_and_retryable_on_phone(viewport):
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport=viewport)
|
||||
page.set_content((FRONTEND / "index.html").read_text())
|
||||
page.add_style_tag(path=FRONTEND / "dashboard.css")
|
||||
page.add_script_tag(path=FRONTEND / "release-receipt.js")
|
||||
result = page.evaluate("""async () => {
|
||||
const calls=[];
|
||||
const values=new Map();
|
||||
const storage={
|
||||
getItem:key=>values.get(key)||null,
|
||||
setItem:(key,value)=>values.set(key,value),
|
||||
removeItem:key=>values.delete(key),
|
||||
};
|
||||
const receipt=createReleaseReceipt({
|
||||
storage,
|
||||
getLogin:()=> 'timmy',
|
||||
listNode:document.querySelector('#release-watchlist'),
|
||||
confirmAction:()=>true,
|
||||
fetchJson:async(path, options={})=>{
|
||||
calls.push({path, method:options.method || 'GET'});
|
||||
if (path.endsWith('/failure')) return {
|
||||
commit_sha:'abc1234', run_id:91, job_index:3,
|
||||
name:'CI / browser', excerpt:'AssertionError: mobile viewport overflow',
|
||||
};
|
||||
if (path.endsWith('/retry')) return {commit_sha:'abc1234', status:'queued'};
|
||||
return {
|
||||
commit_sha:'abc1234', ci_state:'failure', release:null,
|
||||
checks:[{
|
||||
name:'CI / browser with a deliberately long workflow name',
|
||||
state:'failure', description:'Playwright failed at the narrow viewport',
|
||||
url:'https://forge.example/git/stackchain/api/actions/runs/91/jobs/3',
|
||||
recovery:{run_id:91, job_index:3},
|
||||
}],
|
||||
};
|
||||
},
|
||||
});
|
||||
receipt.capture(
|
||||
{repository:'stackchain/api-with-a-long-mobile-name', number:7, key:'stackchain/api-with-a-long-mobile-name#7'},
|
||||
{merge_commit_sha:'abc1234'},
|
||||
);
|
||||
document.querySelector('#release-receipt-sheet').showModal();
|
||||
await receipt.refresh();
|
||||
const review=document.querySelector('.release-failure-summary button');
|
||||
const reviewHeight=review.getBoundingClientRect().height;
|
||||
review.click();
|
||||
await new Promise(resolve=>setTimeout(resolve, 0));
|
||||
const recovery=document.querySelector('.release-failure-recovery');
|
||||
const retry=recovery.querySelector('button');
|
||||
const retryHeight=retry.getBoundingClientRect().height;
|
||||
const excerpt=recovery.querySelector('pre').textContent;
|
||||
const sha=recovery.querySelector('strong').textContent;
|
||||
const job=recovery.querySelector('a').href;
|
||||
const overflow=document.documentElement.scrollWidth > document.documentElement.clientWidth;
|
||||
retry.click();
|
||||
await new Promise(resolve=>setTimeout(resolve, 0));
|
||||
return {
|
||||
calls, reviewHeight, retryHeight, excerpt, sha, job, overflow,
|
||||
state:receipt.restore()[0].status.label,
|
||||
};
|
||||
}""")
|
||||
expect(page.locator("#release-receipt-sheet")).to_be_visible()
|
||||
assert result["reviewHeight"] >= 44
|
||||
assert result["retryHeight"] >= 44
|
||||
assert result["excerpt"] == "AssertionError: mobile viewport overflow"
|
||||
assert result["sha"] == "Merge abc1234"
|
||||
assert result["job"].endswith("/actions/runs/91/jobs/3")
|
||||
assert result["overflow"] is False
|
||||
assert result["state"] == "Checks running"
|
||||
assert [call["method"] for call in result["calls"]] == ["GET", "GET", "POST"]
|
||||
browser.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [
|
||||
{"width": 320, "height": 568},
|
||||
{"width": 390, "height": 844},
|
||||
])
|
||||
def test_failed_release_prepares_a_visible_draft_rollback_receipt_on_phone(viewport):
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport=viewport)
|
||||
page.set_content((FRONTEND / "index.html").read_text())
|
||||
page.add_style_tag(path=FRONTEND / "dashboard.css")
|
||||
page.add_script_tag(path=FRONTEND / "release-receipt.js")
|
||||
result = page.evaluate("""async () => {
|
||||
const values=new Map(), calls=[], opened=[];
|
||||
const receipt=createReleaseReceipt({
|
||||
storage:{getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)},
|
||||
getLogin:()=> 'timmy', listNode:document.querySelector('#release-watchlist'),
|
||||
confirmAction:()=>true, openPull:pull=>opened.push(pull),
|
||||
fetchJson:async(path, options={})=>{
|
||||
calls.push({path,method:options.method||'GET'});
|
||||
if(path.endsWith('/failure')) return {commit_sha:'abc1234',run_id:91,job_index:3,name:'CI / browser',excerpt:'failed'};
|
||||
if(path.endsWith('/rollback')) return {repository:'stackchain/api',number:9,draft:true,rollback_of:'abc1234',url:'https://forge.example/git/stackchain/api/pulls/9'};
|
||||
return {commit_sha:'abc1234',ci_state:'failure',release:null,checks:[{name:'CI / browser',state:'failure',recovery:{run_id:91,job_index:3}}]};
|
||||
},
|
||||
});
|
||||
receipt.capture({repository:'stackchain/api',number:7,key:'stackchain/api#7'},{merge_commit_sha:'abc1234'});
|
||||
document.querySelector('#release-receipt-sheet').showModal();
|
||||
await receipt.refresh();
|
||||
document.querySelector('.release-failure-summary button').click();
|
||||
await new Promise(resolve=>setTimeout(resolve,0));
|
||||
const rollback=[...document.querySelectorAll('.release-failure-actions button')].find(button=>button.textContent==='Prepare rollback PR');
|
||||
const actionHeight=rollback.getBoundingClientRect().height;
|
||||
rollback.click();
|
||||
await new Promise(resolve=>setTimeout(resolve,0));
|
||||
const status=document.querySelector('.release-rollback-status');
|
||||
return {calls,opened,actionHeight,status:status?.textContent||'',overflow:document.documentElement.scrollWidth>document.documentElement.clientWidth};
|
||||
}""")
|
||||
assert result["actionHeight"] >= 44
|
||||
assert result["status"] == "Draft rollback #9 is ready for review."
|
||||
assert result["opened"][0]["number"] == 9
|
||||
assert result["calls"][-1]["path"].endswith("/release-receipt/abc1234/rollback")
|
||||
assert result["overflow"] is False
|
||||
browser.close()
|
||||
@@ -0,0 +1,79 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
|
||||
pytest.skip("rendered authored-pull recovery checks run only in the browser gate", allow_module_level=True)
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
FRONTEND = ROOT / "frontend"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("width", "height"), [(320, 568), (390, 844)])
|
||||
def test_mobile_search_reopens_closed_authored_pull_into_my_work(width, height):
|
||||
html = re.sub(r'<script src="static/[^"]+"></script>', "", (FRONTEND / "index.html").read_text())
|
||||
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch()
|
||||
page = browser.new_page(viewport={"width": width, "height": height})
|
||||
page.set_content(html)
|
||||
page.add_style_tag(path=FRONTEND / "dashboard.css")
|
||||
page.add_script_tag(path=FRONTEND / "search-preview.js")
|
||||
page.locator("#search-preview").evaluate("node => node.classList.add('open')")
|
||||
page.evaluate("""() => {
|
||||
const detail = {
|
||||
repository:'stackchain/web', number:9, kind:'pull', state:'closed',
|
||||
authored_pull_reopenable:true, head_sha:'abc1234',
|
||||
};
|
||||
const button = document.querySelector('#start-search-result');
|
||||
globalThis.renderSearchPreviewStart(detail, {status:'ready'}, button);
|
||||
globalThis.recoveryMetrics = {calls:[], history:['search']};
|
||||
const mutate = globalThis.searchPreviewMutation((path, options) => {
|
||||
globalThis.recoveryMetrics.calls.push({path, body:JSON.parse(options.body)});
|
||||
return Promise.resolve({...detail, state:'open'});
|
||||
});
|
||||
const preview = globalThis.createSearchPreview({
|
||||
fetchJson:async () => detail,
|
||||
mutate,
|
||||
onState:() => {},
|
||||
});
|
||||
preview.open(detail);
|
||||
const recover = globalThis.createSearchAuthoredPullRecovery({
|
||||
confirm:message => window.confirm(message),
|
||||
reopen:target => preview.reopenPull(target),
|
||||
refresh:async () => { globalThis.recoveryMetrics.refreshed = true; },
|
||||
find:() => ({repository:'stackchain/web',number:9,kind:'pull',key:'stackchain/web#9'}),
|
||||
open:item => globalThis.recoveryMetrics.history.push(item.kind),
|
||||
unavailable:message => { globalThis.recoveryMetrics.unavailable = message; },
|
||||
});
|
||||
button.addEventListener('click', () => recover(detail));
|
||||
}""")
|
||||
|
||||
action = page.locator("#start-search-result")
|
||||
expect(action).to_be_visible()
|
||||
expect(action).to_have_text("Reopen in My Work")
|
||||
bounds = action.bounding_box()
|
||||
assert bounds and bounds["height"] >= 44
|
||||
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
|
||||
|
||||
page.once("dialog", lambda dialog: dialog.accept())
|
||||
action.click()
|
||||
page.wait_for_function("globalThis.recoveryMetrics.history.length === 2")
|
||||
metrics = page.evaluate("globalThis.recoveryMetrics")
|
||||
|
||||
assert metrics["calls"] == [{
|
||||
"path": "api/v1/repos/stackchain/web/pulls/9/reopen",
|
||||
"body": {"expected_head_sha": "abc1234"},
|
||||
}]
|
||||
assert metrics["refreshed"] is True
|
||||
assert metrics["history"] == ["search", "pull"]
|
||||
assert "unavailable" not in metrics
|
||||
browser.close()
|
||||
@@ -0,0 +1,67 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
|
||||
pytest.skip("packaged branch-cleanup journey runs only in the browser gate", allow_module_level=True)
|
||||
pytest.importorskip("playwright.sync_api")
|
||||
from playwright.sync_api import expect, sync_playwright
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[2]
|
||||
FRONTEND = ROOT / "frontend"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("viewport", [
|
||||
{"width": 320, "height": 568},
|
||||
{"width": 390, "height": 844},
|
||||
])
|
||||
def test_merged_source_branch_cleanup_is_phone_openable_and_exact(viewport):
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch(headless=True)
|
||||
page = browser.new_page(viewport=viewport)
|
||||
page.set_content((FRONTEND / "index.html").read_text())
|
||||
page.add_style_tag(path=FRONTEND / "dashboard.css")
|
||||
page.add_script_tag(path=FRONTEND / "release-receipt.js")
|
||||
result = page.evaluate("""async () => {
|
||||
const calls=[];
|
||||
const values=new Map();
|
||||
const storage={
|
||||
getItem:key=>values.get(key)||null,
|
||||
setItem:(key,value)=>values.set(key,value),
|
||||
removeItem:key=>values.delete(key),
|
||||
};
|
||||
const receipt=createReleaseReceipt({
|
||||
storage,
|
||||
getLogin:()=> 'timmy',
|
||||
listNode:document.querySelector('#release-watchlist'),
|
||||
confirmAction:()=>true,
|
||||
fetchJson:async(path, options={})=>{
|
||||
calls.push({path, method:options.method, body:options.body});
|
||||
return {deleted:true, source_branch:'timmy/feature', source_head_sha:'abc1234'};
|
||||
},
|
||||
});
|
||||
receipt.capture(
|
||||
{repository:'stackchain/api', number:7, key:'stackchain/api#7'},
|
||||
{merge_commit_sha:'merge456', source_branch:'timmy/feature', source_head_sha:'abc1234', source_repository:'stackchain/api'},
|
||||
);
|
||||
document.querySelector('#release-receipt-sheet').showModal();
|
||||
const button=document.querySelector('.release-watchlist-actions button');
|
||||
const box=button.getBoundingClientRect();
|
||||
const label=button.getAttribute('aria-label');
|
||||
button.click();
|
||||
await new Promise(resolve=>setTimeout(resolve, 0));
|
||||
return {
|
||||
calls, label, height:box.height,
|
||||
branch:document.querySelector('.release-branch-cleanup-status').textContent,
|
||||
overflow:document.documentElement.scrollWidth > document.documentElement.clientWidth,
|
||||
};
|
||||
}""")
|
||||
expect(page.locator("#release-receipt-sheet")).to_be_visible()
|
||||
assert result["height"] >= 44
|
||||
assert result["label"] == "Delete merged source branch timmy/feature at abc1234"
|
||||
assert result["calls"][0]["method"] == "DELETE"
|
||||
assert result["branch"] == "Branch timmy/feature · deleted"
|
||||
assert result["overflow"] is False
|
||||
browser.close()
|
||||
@@ -48,7 +48,7 @@ def test_release_promotion_waits_for_tests_and_bundle():
|
||||
assert release.index("sha256sum -c") < release.index("curl --fail-with-body")
|
||||
|
||||
|
||||
def test_release_promotion_waits_for_packaged_mobile_journeys():
|
||||
def test_release_promotion_waits_for_every_packaged_mobile_journey():
|
||||
text = WORKFLOW.read_text()
|
||||
browser = text[text.index(" browser-journey:") : text.index(" release-candidate:")]
|
||||
release = text[text.index(" release-candidate:") :]
|
||||
@@ -58,28 +58,6 @@ def test_release_promotion_waits_for_packaged_mobile_journeys():
|
||||
assert "pip install -r requirements-e2e.txt" in browser
|
||||
assert "python3 -m playwright install --with-deps chromium" in browser
|
||||
assert 'STACKCHAIN_RUN_RELEASE_E2E: "1"' in browser
|
||||
assert (
|
||||
"python3 -m pytest tests/e2e/test_mobile_offline_issue_release.py "
|
||||
"tests/e2e/test_mobile_search_preview_navigation.py "
|
||||
"tests/e2e/test_mobile_search_week_plan.py "
|
||||
"tests/e2e/test_mobile_find_work_release.py "
|
||||
"tests/e2e/test_mobile_home_bootstrap_release.py "
|
||||
"tests/e2e/test_mobile_sign_out_release.py "
|
||||
"tests/e2e/test_mobile_today_handoff_release.py "
|
||||
"tests/e2e/test_mobile_today_wrap_up_release.py "
|
||||
"tests/e2e/test_mobile_today_summary_release.py "
|
||||
"tests/e2e/test_mobile_tomorrow_conflict_release.py "
|
||||
"tests/e2e/test_mobile_week_ahead_release.py "
|
||||
"tests/e2e/test_mobile_today_week_reschedule_release.py "
|
||||
"tests/e2e/test_mobile_wrap_up_handoff_release.py "
|
||||
"tests/e2e/test_mobile_following_release.py "
|
||||
"tests/e2e/test_mobile_detail_watch_release.py -q"
|
||||
) in browser
|
||||
assert "python3 -m pytest tests/e2e -q" in browser
|
||||
assert "test_mobile_" not in browser
|
||||
assert "needs: [lint, build-release, browser-journey]" in release
|
||||
|
||||
|
||||
def test_browser_job_runs_packaged_today_week_reschedule_journey():
|
||||
text = WORKFLOW.read_text()
|
||||
browser = text[text.index(" browser-journey:") : text.index(" release-candidate:")]
|
||||
|
||||
assert "tests/e2e/test_mobile_today_week_reschedule_release.py" in browser
|
||||
@@ -827,6 +827,143 @@ if (!states.some(state => state.status === 'reopened')) throw new Error('reopen
|
||||
subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
|
||||
|
||||
def test_search_preview_closed_authored_pull_reopen_sends_head_guard_to_pull_api():
|
||||
script = f"""
|
||||
require({json.dumps(str(SEARCH_PREVIEW))});
|
||||
(async () => {{
|
||||
const calls = [];
|
||||
const mutate = globalThis.searchPreviewMutation(async (path, options) => {{
|
||||
calls.push({{path, options}});
|
||||
return {{repository:'stackchain/web',number:9,state:'open',head_sha:'abc1234'}};
|
||||
}});
|
||||
const detail = {{
|
||||
repository:'stackchain/web',number:9,kind:'pull',state:'closed',
|
||||
authored_pull_reopenable:true,head_sha:'abc1234',
|
||||
}};
|
||||
const result = await mutate(detail, 'reopen-pull');
|
||||
process.stdout.write(JSON.stringify({{calls,result}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {
|
||||
"calls": [{
|
||||
"path": "api/v1/repos/stackchain/web/pulls/9/reopen",
|
||||
"options": {
|
||||
"method": "PATCH",
|
||||
"headers": {"Content-Type": "application/json"},
|
||||
"body": '{"expected_head_sha":"abc1234"}',
|
||||
},
|
||||
}],
|
||||
"result": {
|
||||
"repository": "stackchain/web",
|
||||
"number": 9,
|
||||
"state": "open",
|
||||
"head_sha": "abc1234",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_search_preview_closed_authored_pull_exposes_reopen_in_my_work_action():
|
||||
script = f"""
|
||||
require({json.dumps(str(SEARCH_PREVIEW))});
|
||||
const detail = {{
|
||||
repository:'stackchain/web',number:9,kind:'pull',state:'closed',
|
||||
authored_pull_reopenable:true,head_sha:'abc1234',
|
||||
}};
|
||||
const ready = {{hidden:true,textContent:'',disabled:false}};
|
||||
globalThis.renderSearchPreviewStart(detail, {{status:'ready'}}, ready);
|
||||
const pending = {{hidden:true,textContent:'',disabled:false}};
|
||||
globalThis.renderSearchPreviewStart(detail, {{status:'reopening'}}, pending);
|
||||
process.stdout.write(JSON.stringify({{ready,pending}}));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {
|
||||
"ready": {
|
||||
"hidden": False,
|
||||
"textContent": "Reopen in My Work",
|
||||
"disabled": False,
|
||||
},
|
||||
"pending": {
|
||||
"hidden": False,
|
||||
"textContent": "Reopen in My Work",
|
||||
"disabled": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_search_preview_closed_authored_pull_reopen_is_single_flight():
|
||||
script = f"""
|
||||
const createSearchPreview = require({json.dumps(str(SEARCH_PREVIEW))});
|
||||
(async () => {{
|
||||
let calls = 0;
|
||||
let resolveMutation;
|
||||
const states = [];
|
||||
const detail = {{
|
||||
repository:'stackchain/web',number:9,kind:'pull',state:'closed',
|
||||
authored_pull_reopenable:true,head_sha:'abc1234',
|
||||
}};
|
||||
const preview = createSearchPreview({{
|
||||
fetchJson:async () => detail,
|
||||
mutate:(_detail, action) => {{
|
||||
if (action !== 'reopen-pull') throw new Error('wrong action');
|
||||
calls += 1;
|
||||
return new Promise(resolve => {{ resolveMutation = resolve; }});
|
||||
}},
|
||||
onState:state => states.push(state),
|
||||
}});
|
||||
await preview.open(detail);
|
||||
const first = preview.reopenPull(detail);
|
||||
const second = preview.reopenPull(detail);
|
||||
if (first !== second || calls !== 1) throw new Error('pull recovery was not single-flight');
|
||||
resolveMutation({{...detail,state:'open'}});
|
||||
await first;
|
||||
process.stdout.write(JSON.stringify({{calls,status:states.at(-1).status}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
assert json.loads(result.stdout) == {"calls": 1, "status": "reopened"}
|
||||
|
||||
|
||||
def test_authored_pull_recovery_confirms_refreshes_and_opens_above_search_history():
|
||||
script = f"""
|
||||
require({json.dumps(str(SEARCH_PREVIEW))});
|
||||
(async () => {{
|
||||
const events = [];
|
||||
const history = ['search'];
|
||||
const detail = {{repository:'stackchain/web',number:9,kind:'pull',head_sha:'abc1234'}};
|
||||
const item = {{repository:'stackchain/web',number:9,kind:'pull',key:'stackchain/web#9'}};
|
||||
const recover = globalThis.createSearchAuthoredPullRecovery({{
|
||||
confirm:message => {{ events.push(['confirm',message]); return true; }},
|
||||
reopen:target => {{ events.push(['reopen',target.head_sha]); return Promise.resolve({{...target,state:'open'}}); }},
|
||||
refresh:() => {{ events.push(['refresh']); return Promise.resolve(); }},
|
||||
find:target => target.number === 9 ? item : null,
|
||||
open:opened => {{ events.push(['open',opened.key]); history.push('pull'); }},
|
||||
unavailable:message => events.push(['unavailable',message]),
|
||||
}});
|
||||
const outcome = await recover(detail);
|
||||
process.stdout.write(JSON.stringify({{events,history,outcome}}));
|
||||
}})().catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
payload = json.loads(result.stdout)
|
||||
assert payload["events"] == [
|
||||
["confirm", "Reopen stackchain/web #9?"],
|
||||
["reopen", "abc1234"],
|
||||
["refresh"],
|
||||
["open", "stackchain/web#9"],
|
||||
]
|
||||
assert payload["history"] == ["search", "pull"]
|
||||
assert payload["outcome"] == "opened"
|
||||
|
||||
|
||||
def test_search_preview_watch_is_single_flight_and_keeps_visible_context_on_failure():
|
||||
script = f"""
|
||||
const createSearchPreview = require({json.dumps(str(SEARCH_PREVIEW))});
|
||||
@@ -1159,9 +1296,11 @@ def test_assigned_pull_preview_hands_off_to_existing_my_work_sheet_without_claim
|
||||
def test_requested_pull_preview_opens_native_review_without_assignment_mutation():
|
||||
html = dashboard_bundle_text()
|
||||
css = (FRONTEND / "dashboard.css").read_text()
|
||||
preview = SEARCH_PREVIEW.read_text()
|
||||
|
||||
assert "startButton.hidden = !(detail.reviewable" in html
|
||||
assert "detail.reviewable ? 'Review now'" in html
|
||||
assert "renderSearchPreviewStart(detail, state, startButton)" in html
|
||||
assert "button.hidden = !(detail.reviewable" in preview
|
||||
assert "detail.reviewable ? 'Review now'" in preview
|
||||
handler = html.split(
|
||||
"qs('#start-search-result').addEventListener('click'", 1
|
||||
)[1].split("qs('#close-whiteboard')", 1)[0]
|
||||
@@ -1176,9 +1315,10 @@ def test_requested_pull_preview_opens_native_review_without_assignment_mutation(
|
||||
def test_search_preview_offers_assign_and_start_for_eligible_issues():
|
||||
html = dashboard_bundle_text()
|
||||
css = (FRONTEND / "dashboard.css").read_text()
|
||||
preview = SEARCH_PREVIEW.read_text()
|
||||
|
||||
assert 'id="start-search-result"' in html
|
||||
assert "(detail.assigned_to_me ? 'Start in Today' : 'Assign & start')" in html
|
||||
assert "(detail.assigned_to_me ? 'Start in Today' : 'Assign & start')" in preview
|
||||
assert "const searchAssignAndStart = createSearchStart(detail => searchPreview.claim(detail))" in html
|
||||
assert "searchAssignAndStart.run(detail, { alreadyOwned: detail.assigned_to_me })" in html
|
||||
assert ".search-preview-primary-actions" in css
|
||||
@@ -1332,9 +1472,10 @@ process.stdout.write(JSON.stringify({{outcome, refreshes, messages}}));
|
||||
|
||||
def test_closed_issue_preview_reopens_then_resumes_through_capacity_guard():
|
||||
html = dashboard_bundle_text()
|
||||
preview = SEARCH_PREVIEW.read_text()
|
||||
|
||||
assert "detail.reopenable ? 'Reopen & resume'" in html
|
||||
assert "mutate:(detail,action)=>fetchReviewJson(" in html
|
||||
assert "detail.reopenable ? 'Reopen & resume'" in preview
|
||||
assert "mutate:searchPreviewMutation(fetchReviewJson)" in html
|
||||
handler = html.split("qs('#start-search-result').addEventListener('click'", 1)[1].split(
|
||||
"qs('#close-whiteboard')", 1
|
||||
)[0]
|
||||
|
||||
@@ -303,4 +303,4 @@ async def test_unread_update_offers_reply_mark_read_and_next_independent_of_toda
|
||||
assert '.update-reply-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr));' in html
|
||||
assert '.update-reply-actions button { min-height:44px;' in html
|
||||
worker = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
assert "stackchain-dashboard-shell-v138" in worker
|
||||
assert "stackchain-dashboard-shell-v139" in worker
|
||||
@@ -0,0 +1,203 @@
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from src import gitea_proxy
|
||||
from src import main
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_pull_creation_operations():
|
||||
main._authored_action_operations.clear()
|
||||
main._idempotency_ledger.clear()
|
||||
yield
|
||||
main._authored_action_operations.clear()
|
||||
main._idempotency_ledger.clear()
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pull_creation_options_return_visible_repository_branches(monkeypatch):
|
||||
async def access(repository):
|
||||
assert repository == "stackchain/api"
|
||||
return {"full_name": repository, "default_branch": "main", "permissions": {"push": True}}
|
||||
|
||||
async def branches(repository):
|
||||
assert repository == "stackchain/api"
|
||||
return [
|
||||
{"name": "feature/mobile", "commit": {"id": "abc1234"}},
|
||||
{"name": "main", "commit": {"id": "def5678"}},
|
||||
]
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "repository_access", access)
|
||||
monkeypatch.setattr(main.gitea_proxy, "repo_branches", branches, raising=False)
|
||||
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/api/v1/repos/stackchain/api/pull-creation-options")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["cache-control"] == "no-store"
|
||||
assert response.json() == {
|
||||
"default_branch": "main",
|
||||
"branches": [
|
||||
{"name": "feature/mobile", "sha": "abc1234"},
|
||||
{"name": "main", "sha": "def5678"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_create_pull_endpoint_returns_confirmed_mobile_pull(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def access(repository):
|
||||
return {"full_name": repository, "permissions": {"push": True}}
|
||||
|
||||
async def create(repository, *, head, base, title, body, draft, expected_head_sha):
|
||||
calls.append((repository, head, base, title, body, draft, expected_head_sha))
|
||||
return {
|
||||
"number": 42,
|
||||
"repository": repository,
|
||||
"title": title,
|
||||
"body": body,
|
||||
"head": {"ref": head, "sha": expected_head_sha},
|
||||
"base": {"ref": base},
|
||||
"draft": draft,
|
||||
"state": "open",
|
||||
"url": "https://forge.example/stackchain/api/pulls/42",
|
||||
"existing": False,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "repository_access", access)
|
||||
monkeypatch.setattr(main.gitea_proxy, "create_pull", create, raising=False)
|
||||
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/api/pulls",
|
||||
headers={"Idempotency-Key": "mobile-create-42"},
|
||||
json={
|
||||
"head": "feature/mobile",
|
||||
"base": "main",
|
||||
"title": " Ship mobile create ",
|
||||
"body": " Context ",
|
||||
"draft": True,
|
||||
"expected_head_sha": "abc1234",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 201
|
||||
assert response.headers["cache-control"] == "no-store"
|
||||
assert response.json()["number"] == 42
|
||||
assert calls == [
|
||||
("stackchain/api", "feature/mobile", "main", "Ship mobile create", "Context", True, "abc1234")
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_create_pull_revalidates_head_and_confirms_created_pull():
|
||||
requests = []
|
||||
|
||||
async def handler(request):
|
||||
requests.append(request)
|
||||
if request.method == "GET" and request.url.path.endswith("/branches/feature/mobile"):
|
||||
return httpx.Response(200, json={"name": "feature/mobile", "commit": {"id": "abc1234"}})
|
||||
if request.method == "GET" and request.url.path.endswith("/pulls"):
|
||||
return httpx.Response(200, json=[])
|
||||
if request.method == "POST" and request.url.path.endswith("/pulls"):
|
||||
return httpx.Response(201, json={
|
||||
"number": 42,
|
||||
"title": "Ship mobile create",
|
||||
"body": "Context",
|
||||
"state": "open",
|
||||
"draft": True,
|
||||
"head": {"ref": "feature/mobile", "sha": "abc1234"},
|
||||
"base": {"ref": "main"},
|
||||
"user": {"login": "timmy"},
|
||||
"html_url": "https://forge.alexanderwhitestone.com/git/stackchain/api/pulls/42",
|
||||
})
|
||||
return httpx.Response(404)
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
result = await gitea_proxy.create_pull(
|
||||
"stackchain/api",
|
||||
head="feature/mobile",
|
||||
base="main",
|
||||
title="Ship mobile create",
|
||||
body="Context",
|
||||
draft=True,
|
||||
expected_head_sha="abc1234",
|
||||
)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert result["number"] == 42
|
||||
assert result["head"] == {"ref": "feature/mobile", "sha": "abc1234"}
|
||||
assert result["author"] == "timmy"
|
||||
assert result["existing"] is False
|
||||
mutation = next(request for request in requests if request.method == "POST")
|
||||
assert mutation.read() == b'{"head":"feature/mobile","base":"main","title":"Ship mobile create","body":"Context","draft":true}'
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_gitea_create_pull_returns_existing_source_base_without_mutation():
|
||||
requests = []
|
||||
existing = {
|
||||
"number": 41,
|
||||
"title": "Already open",
|
||||
"body": "Existing context",
|
||||
"state": "open",
|
||||
"draft": False,
|
||||
"head": {"ref": "feature/mobile", "sha": "abc1234"},
|
||||
"base": {"ref": "main"},
|
||||
"user": {"login": "timmy"},
|
||||
"html_url": "https://forge.alexanderwhitestone.com/git/stackchain/api/pulls/41",
|
||||
}
|
||||
|
||||
async def handler(request):
|
||||
requests.append(request)
|
||||
if "/branches/" in request.url.path:
|
||||
return httpx.Response(200, json={"name": "feature/mobile", "commit": {"id": "abc1234"}})
|
||||
if request.method == "GET" and request.url.path.endswith("/pulls"):
|
||||
return httpx.Response(200, json=[existing])
|
||||
return httpx.Response(500)
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
result = await gitea_proxy.create_pull(
|
||||
"stackchain/api", head="feature/mobile", base="main",
|
||||
title="Duplicate attempt", body="", draft=True,
|
||||
expected_head_sha="abc1234",
|
||||
)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert result["number"] == 41
|
||||
assert result["existing"] is True
|
||||
assert all(request.method != "POST" for request in requests)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_create_pull_endpoint_reports_stale_source_without_retrying(monkeypatch):
|
||||
async def access(repository):
|
||||
return {"full_name": repository, "permissions": {"push": True}}
|
||||
|
||||
async def stale(*args, **kwargs):
|
||||
raise gitea_proxy.PullCreateConflictError("Source branch changed before pull creation")
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "repository_access", access)
|
||||
monkeypatch.setattr(main.gitea_proxy, "create_pull", stale)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.post(
|
||||
"/api/v1/repos/stackchain/api/pulls",
|
||||
json={
|
||||
"head": "feature/mobile", "base": "main", "title": "Ship it",
|
||||
"expected_head_sha": "abc1234",
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == 409
|
||||
assert response.json() == {
|
||||
"error": "The source branch changed. Refresh branches before creating the pull request."
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).parents[1]
|
||||
MODULE = ROOT / "frontend" / "create-pull-sheet.js"
|
||||
|
||||
|
||||
def run_node(scenario: str) -> dict:
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(MODULE))});
|
||||
{scenario}
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], text=True, capture_output=True, cwd=ROOT)
|
||||
assert result.returncode == 0, result.stderr
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def test_create_pull_controller_loads_branches_and_defaults_base():
|
||||
result = run_node("""
|
||||
const calls=[];
|
||||
const controller=createPullSheet.createController({
|
||||
request:async (url) => {
|
||||
calls.push(url);
|
||||
return {default_branch:'main',branches:[
|
||||
{name:'feature/mobile',sha:'abc1234'},
|
||||
{name:'main',sha:'def5678'}
|
||||
]};
|
||||
},
|
||||
storage:{getItem:()=>null,setItem:()=>{}},
|
||||
login:'timmy'
|
||||
});
|
||||
controller.selectRepository('stackchain/api').then(value => {
|
||||
process.stdout.write(JSON.stringify({value,calls,state:controller.state()}));
|
||||
}).catch(error=>{console.error(error);process.exit(1)});
|
||||
""")
|
||||
assert result["calls"] == ["api/v1/repos/stackchain/api/pull-creation-options"]
|
||||
assert result["state"]["base"] == "main"
|
||||
assert result["state"]["head"] == "feature/mobile"
|
||||
assert result["state"]["expected_head_sha"] == "abc1234"
|
||||
|
||||
|
||||
def test_create_pull_controller_submits_idempotently_and_keeps_draft_on_failure():
|
||||
result = run_node("""
|
||||
const calls=[]; const saved=[]; let fail=true;
|
||||
const controller=createPullSheet.createController({
|
||||
request:async (url, options) => {
|
||||
calls.push([url,options]);
|
||||
if (!options) return {default_branch:'main',branches:[{name:'topic',sha:'abc1234'},{name:'main',sha:'def5678'}]};
|
||||
if (fail) { fail=false; throw new Error('offline'); }
|
||||
return {number:9,repository:'acme/app',head:{ref:'topic',sha:'abc1234'},base:{ref:'main'},draft:true};
|
||||
},
|
||||
storage:{getItem:()=>null,setItem:(key,value)=>saved.push([key,JSON.parse(value)])},
|
||||
login:'timmy', createId:()=> 'stable-id'
|
||||
});
|
||||
(async()=>{
|
||||
await controller.selectRepository('acme/app');
|
||||
controller.update({title:'Ship it',body:'Context'});
|
||||
let error=''; try { await controller.submit(); } catch (caught) { error=caught.message; }
|
||||
const retained=controller.state();
|
||||
const confirmed=await controller.submit();
|
||||
process.stdout.write(JSON.stringify({calls,error,retained,confirmed,saved}));
|
||||
})().catch(error=>{console.error(error);process.exit(1)});
|
||||
""")
|
||||
assert result["error"] == "offline"
|
||||
assert result["retained"]["title"] == "Ship it"
|
||||
posts = [call for call in result["calls"] if call[1]]
|
||||
assert len(posts) == 2
|
||||
assert posts[0][1]["headers"]["Idempotency-Key"] == "stable-id"
|
||||
assert posts[1][1]["headers"]["Idempotency-Key"] == "stable-id"
|
||||
assert posts[0][1]["body"]["expected_head_sha"] == "abc1234"
|
||||
assert result["confirmed"]["number"] == 9
|
||||
|
||||
|
||||
def test_create_pull_controller_restores_only_the_current_accounts_draft():
|
||||
result = run_node("""
|
||||
const values={
|
||||
'stackchain.create-pull.v1.timmy':JSON.stringify({repository:'acme/app',head:'topic',base:'main',title:'Saved title',body:'Saved body',draft:false}),
|
||||
'stackchain.create-pull.v1.alexander':JSON.stringify({repository:'private/repo',title:'Other account'})
|
||||
};
|
||||
const controller=createPullSheet.createController({
|
||||
request:async()=>({}), storage:{getItem:key=>values[key] || null,setItem:()=>{}}, login:'Timmy'
|
||||
});
|
||||
process.stdout.write(JSON.stringify(controller.state()));
|
||||
""")
|
||||
assert result == {
|
||||
"repository": "acme/app",
|
||||
"branches": [],
|
||||
"head": "topic",
|
||||
"base": "main",
|
||||
"expected_head_sha": "",
|
||||
"title": "Saved title",
|
||||
"body": "Saved body",
|
||||
"draft": False,
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_pull_creation_sheet_is_packaged_and_touch_safe():
|
||||
html = (ROOT / "frontend" / "index.html").read_text()
|
||||
css = (ROOT / "frontend" / "dashboard.css").read_text()
|
||||
bundle = (ROOT / "src" / "frontend_bundle.py").read_text()
|
||||
|
||||
assert 'id="create-pull-sheet" role="dialog" aria-modal="true"' in html
|
||||
assert 'id="create-pull-form"' in html
|
||||
assert 'id="create-pull-repository"' in html
|
||||
assert 'id="create-pull-head"' in html
|
||||
assert 'id="create-pull-base"' in html
|
||||
assert 'id="submit-create-pull"' in html
|
||||
assert 'static/create-pull-sheet.js' in bundle
|
||||
assert ".create-pull-panel button" in css
|
||||
assert "min-height:44px" in css.replace(" ", "")
|
||||
|
||||
|
||||
def test_create_pull_binding_renders_branch_receipt_and_created_pull():
|
||||
result = run_node("""
|
||||
const rendered=[]; const statuses=[]; const opened=[];
|
||||
const controller={
|
||||
selectRepository:async repository=>({repository,branches:[{name:'topic',sha:'abc1234'},{name:'main',sha:'def5678'}],head:'topic',base:'main',expected_head_sha:'abc1234'}),
|
||||
update:values=>values,
|
||||
submit:async()=>({number:12,repository:'acme/app',existing:false})
|
||||
};
|
||||
const binding=createPullSheet.createBinding({controller,
|
||||
render:state=>rendered.push(state), status:value=>statuses.push(value),
|
||||
onCreated:value=>opened.push(value)
|
||||
});
|
||||
(async()=>{
|
||||
await binding.repositoryChanged('acme/app');
|
||||
await binding.submit();
|
||||
process.stdout.write(JSON.stringify({rendered,statuses,opened}));
|
||||
})().catch(error=>{console.error(error);process.exit(1)});
|
||||
""")
|
||||
assert result["rendered"][0]["expected_head_sha"] == "abc1234"
|
||||
assert result["statuses"][-1] == "Pull request #12 created."
|
||||
assert result["opened"][0]["number"] == 12
|
||||
|
||||
|
||||
def test_dashboard_wires_create_pull_inside_lazy_issue_capture_chunk():
|
||||
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
|
||||
module = MODULE.read_text()
|
||||
assert "cp.b();" not in dashboard
|
||||
assert "else cp.b();" in module
|
||||
@@ -2,6 +2,7 @@ import asyncio
|
||||
import sqlite3
|
||||
import threading
|
||||
import time
|
||||
from typing import get_args
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
import httpx
|
||||
@@ -9,10 +10,14 @@ import pytest
|
||||
from fastapi import Request
|
||||
|
||||
from src import main
|
||||
from src.session_store import SessionStoreError
|
||||
from src.session_store import SessionStatus, SessionStoreError
|
||||
from src.views import FRONTEND_BUILD
|
||||
|
||||
|
||||
def test_release_rollback_is_a_supported_step_up_action():
|
||||
assert "prepare_release_rollback" in get_args(main.StepUpAction)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def access_control(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("STACKCHAIN_DASHBOARD_AUTH_MODE", "operator")
|
||||
@@ -24,6 +29,83 @@ def access_control(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("STACKCHAIN_LOGIN_ATTEMPT_DB", str(tmp_path / "login-attempts.sqlite3"))
|
||||
monkeypatch.setenv("STACKCHAIN_LOGIN_MAX_FAILURES", "3")
|
||||
monkeypatch.setenv("STACKCHAIN_LOGIN_WINDOW_SECONDS", "60")
|
||||
async def upstream_user():
|
||||
return {"id": 42, "login": "timmy"}
|
||||
|
||||
monkeypatch.setattr(main, "current_user", upstream_user)
|
||||
|
||||
|
||||
def test_signed_session_carries_bound_upstream_identity(access_control):
|
||||
signed, _ = main.dashboard_auth.issue_session(
|
||||
now=1_000,
|
||||
principal_id=42,
|
||||
principal_login="timmy",
|
||||
)
|
||||
|
||||
verification = main.dashboard_auth.verify_session_with_reason(signed, now=1_001)
|
||||
|
||||
assert verification.session is not None
|
||||
assert verification.session.principal_id == 42
|
||||
assert verification.session.principal_login == "timmy"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_session_is_blocked_when_upstream_account_changes(
|
||||
access_control, monkeypatch
|
||||
):
|
||||
identity = {"id": 42, "login": "timmy"}
|
||||
|
||||
async def upstream_user():
|
||||
return dict(identity)
|
||||
|
||||
monkeypatch.setattr(main, "current_user", upstream_user)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
signed_in = await client.post(
|
||||
"/api/v1/session",
|
||||
json={"access_token": "correct horse battery staple"},
|
||||
)
|
||||
identity.update(login="renamed-timmy")
|
||||
same_principal = await client.get("/api/v1/security-events")
|
||||
identity.update(id=84, login="other-operator")
|
||||
protected = await client.get("/api/v1/security-events")
|
||||
|
||||
assert signed_in.status_code == 200
|
||||
assert same_principal.status_code == 200
|
||||
assert protected.status_code == 401
|
||||
assert protected.json() == {
|
||||
"detail": "Connected Gitea account changed; sign in again",
|
||||
"code": "session_idle",
|
||||
"reason": "upstream_identity_changed",
|
||||
"previous_login": "timmy",
|
||||
"current_login": "other-operator",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_session_identity_lookup_outage_is_retryable(access_control, monkeypatch):
|
||||
available = True
|
||||
|
||||
async def upstream_user():
|
||||
if not available:
|
||||
raise RuntimeError("credential lookup details")
|
||||
return {"id": 42, "login": "timmy"}
|
||||
|
||||
monkeypatch.setattr(main, "current_user", upstream_user)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
signed_in = await client.post(
|
||||
"/api/v1/session",
|
||||
json={"access_token": "correct horse battery staple"},
|
||||
)
|
||||
available = False
|
||||
protected = await client.get("/api/v1/security-events")
|
||||
|
||||
assert signed_in.status_code == 200
|
||||
assert protected.status_code == 503
|
||||
assert protected.json() == {"detail": "Gitea identity is temporarily unavailable"}
|
||||
assert protected.headers["retry-after"] == "5"
|
||||
assert "credential lookup" not in protected.text
|
||||
|
||||
|
||||
async def fresh_grant(client, action: str, target: str) -> str:
|
||||
@@ -43,6 +125,84 @@ async def fresh_grant(client, action: str, target: str) -> str:
|
||||
return response.json()["grant"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_source_branch_deletion_accepts_exact_one_time_fresh_authorization(
|
||||
access_control, monkeypatch
|
||||
):
|
||||
lifecycle = []
|
||||
|
||||
class Journal:
|
||||
def record(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def reserve(self, kind, *, target):
|
||||
lifecycle.append(("reserve", kind, target))
|
||||
return "cleanup-operation"
|
||||
|
||||
def finalize(self, operation_id):
|
||||
lifecycle.append(("finalize", operation_id))
|
||||
|
||||
def discard(self, operation_id):
|
||||
lifecycle.append(("discard", operation_id))
|
||||
|
||||
async def cleanup(repository, number, source_branch, expected_head_sha):
|
||||
lifecycle.append(
|
||||
("delete", repository, number, source_branch, expected_head_sha)
|
||||
)
|
||||
return {"number": number, "deleted": True}
|
||||
|
||||
monkeypatch.setattr(main, "_security_event_store", lambda: Journal())
|
||||
monkeypatch.setattr(main.gitea_proxy, "delete_merged_source_branch", cleanup)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="https://test") as client:
|
||||
signed_in = await client.post(
|
||||
"/api/v1/session",
|
||||
json={"access_token": "correct horse battery staple", "device_label": "Phone"},
|
||||
)
|
||||
assert signed_in.status_code == 200
|
||||
headers = {
|
||||
"Origin": "https://test",
|
||||
"X-CSRF-Token": client.cookies["stackchain_csrf"],
|
||||
}
|
||||
request = {
|
||||
"source_branch": "timmy/feature",
|
||||
"expected_head_sha": "abc1234",
|
||||
}
|
||||
path = "/api/v1/repos/stackchain/api/pulls/7/source-branch"
|
||||
|
||||
challenged = await client.request("DELETE", path, json=request, headers=headers)
|
||||
grant = await fresh_grant(
|
||||
client, "delete_source_branch", "stackchain/api#7@abc1234"
|
||||
)
|
||||
deleted = await client.request(
|
||||
"DELETE",
|
||||
path,
|
||||
json=request,
|
||||
headers={**headers, "X-Step-Up-Grant": grant},
|
||||
)
|
||||
replayed = await client.request(
|
||||
"DELETE",
|
||||
path,
|
||||
json=request,
|
||||
headers={**headers, "X-Step-Up-Grant": grant},
|
||||
)
|
||||
|
||||
assert challenged.status_code == 428
|
||||
assert challenged.json()["detail"] == {
|
||||
"detail": "Fresh authorization required",
|
||||
"code": "step_up_required",
|
||||
"action": "delete_source_branch",
|
||||
"target": "stackchain/api#7@abc1234",
|
||||
}
|
||||
assert deleted.status_code == 200
|
||||
assert replayed.status_code == 428
|
||||
assert lifecycle == [
|
||||
("reserve", "source_branch_deleted", "stackchain/api#7@abc1234"),
|
||||
("delete", "stackchain/api", 7, "timmy/feature", "abc1234"),
|
||||
("finalize", "cleanup-operation"),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_passkey_enrollment_options_require_fresh_authorization_and_are_one_time(
|
||||
access_control,
|
||||
@@ -1821,7 +1981,7 @@ async def test_logout_revokes_a_captured_cookie_before_gitea(access_control, mon
|
||||
assert before.status_code == 200
|
||||
assert after.status_code == 401
|
||||
assert after.headers["cache-control"] == "no-store"
|
||||
assert calls == 1
|
||||
assert calls == 4
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -1835,7 +1995,9 @@ async def test_session_registry_latency_does_not_block_the_event_loop(access_con
|
||||
class SlowStore:
|
||||
def status(self, session_id, expires_at, *, idle_timeout_seconds):
|
||||
time.sleep(0.15)
|
||||
return "active"
|
||||
return SessionStatus(
|
||||
"active", principal_id=42, principal_login="timmy"
|
||||
)
|
||||
|
||||
monkeypatch.setattr(main.dashboard_auth, "_session_store", lambda now=None: SlowStore())
|
||||
private_request = asyncio.create_task(client.get("/api/v1/session"))
|
||||
@@ -2001,7 +2163,9 @@ async def test_single_session_revocation_does_not_block_the_event_loop(
|
||||
class SlowStore:
|
||||
def status(self, session_id, expires_at, *, idle_timeout_seconds):
|
||||
time.sleep(0.02)
|
||||
return "active"
|
||||
return SessionStatus(
|
||||
"active", principal_id=42, principal_login="timmy"
|
||||
)
|
||||
|
||||
def revoke(self, session_id):
|
||||
time.sleep(0.15)
|
||||
@@ -2043,6 +2207,7 @@ async def test_session_registry_read_failure_fails_closed_before_gitea(
|
||||
await client.post(
|
||||
"/api/v1/session", json={"access_token": "correct horse battery staple"}
|
||||
)
|
||||
called = False
|
||||
|
||||
class BrokenStore:
|
||||
def status(self, session_id, expires_at, *, idle_timeout_seconds):
|
||||
@@ -2091,7 +2256,9 @@ async def test_logout_registry_failure_does_not_claim_revocation(access_control,
|
||||
|
||||
class BrokenStore:
|
||||
def status(self, session_id, expires_at, *, idle_timeout_seconds):
|
||||
return "active"
|
||||
return SessionStatus(
|
||||
"active", principal_id=42, principal_login="timmy"
|
||||
)
|
||||
|
||||
def revoke(self, session_id):
|
||||
raise SessionStoreError("database path and secret details")
|
||||
|
||||
@@ -558,6 +558,28 @@ process.stdout.write(JSON.stringify(state));
|
||||
assert result["replacedAfterDeletion"] is True
|
||||
|
||||
|
||||
def test_upstream_identity_change_preserves_private_work_and_requires_sign_in():
|
||||
result = run_session_scenario(
|
||||
"""
|
||||
state.responseStatus = 401;
|
||||
state.responsePayload = {
|
||||
detail:'Connected Gitea account changed; sign in again',
|
||||
code:'session_idle', reason:'upstream_identity_changed',
|
||||
previous_login:'timmy', current_login:'other-operator',
|
||||
};
|
||||
await boundary.fetch('/dashboard/api/v1/live');
|
||||
state.remaining = Array.from(storage.values.keys());
|
||||
process.stdout.write(JSON.stringify(state));
|
||||
"""
|
||||
)
|
||||
|
||||
assert result["remaining"] == ["stackchain.private", "gitea.preference"]
|
||||
assert result["deletedDatabases"] == []
|
||||
assert result["deletedCaches"] == []
|
||||
assert result["workerMessages"] == []
|
||||
assert result["replaced"] == ["/dashboard/login?reason=session-idle"]
|
||||
|
||||
|
||||
def test_idle_response_locks_without_clearing_private_queued_work():
|
||||
result = run_session_scenario(
|
||||
"""
|
||||
|
||||
@@ -130,7 +130,8 @@ def test_detail_watch_is_wired_into_both_mobile_work_details_and_bundle():
|
||||
assert 'pullDetailWatch.open(item)' in dashboard
|
||||
assert '#watch-issue-detail' in css
|
||||
assert '#watch-pull-detail' in css
|
||||
assert 'tests/e2e/test_mobile_detail_watch_release.py' in workflow
|
||||
assert "python3 -m pytest tests/e2e -q" in workflow
|
||||
assert (ROOT / "tests/e2e/test_mobile_detail_watch_release.py").is_file()
|
||||
|
||||
|
||||
def test_detail_watch_ignores_a_late_subscription_response_for_the_previous_item():
|
||||
|
||||
@@ -593,7 +593,7 @@ process.stdout.write(JSON.stringify({{
|
||||
assert ".following-disposition-mode" in css
|
||||
assert "if (searchPreviewReturnKind === 'following')" in dashboard
|
||||
assert "e.key === 'Escape' && searchPreviewReturnKind === 'following'" in dashboard
|
||||
assert "stackchain-dashboard-shell-v138" in service_worker
|
||||
assert "stackchain-dashboard-shell-v139" in service_worker
|
||||
|
||||
|
||||
def test_prepare_today_lazily_refreshes_and_directly_reviews_following():
|
||||
|
||||
@@ -100,6 +100,32 @@ async def test_filed_work_page_loads_open_and_closed_authored_issues_with_a_dist
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_authored_pull_page_loads_open_created_pulls_with_a_distinct_reason():
|
||||
requests = []
|
||||
|
||||
def upstream(request):
|
||||
requests.append(str(request.url))
|
||||
return httpx.Response(200, headers={"X-Total-Count": "3"}, json=[{
|
||||
"id": 901, "number": 41, "title": "Ship mobile flow", "state": "open",
|
||||
"user": {"login": "timmy"},
|
||||
"repository": {"full_name": "stackchain/dashboard"},
|
||||
"html_url": "http://127.0.0.1:3000/stackchain/dashboard/pulls/41",
|
||||
}])
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(upstream))
|
||||
try:
|
||||
result = await gitea_proxy.work_page("authored", page=1)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert requests == [
|
||||
"http://127.0.0.1:3000/api/v1/repos/issues/search?state=open&created=true&type=pulls&limit=50&page=1"
|
||||
]
|
||||
assert result["total"] == 3
|
||||
assert result["items"][0]["work_reasons"] == ["authored_by_me"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_issue_context_merges_self_assigned_and_filed_streams_without_duplicates(monkeypatch):
|
||||
async def page(stream, page=1, limit=50):
|
||||
@@ -628,7 +654,7 @@ async def test_confirmed_claim_is_removed_from_retained_available_snapshot(monke
|
||||
async def test_initial_work_collections_expose_independent_pagination(monkeypatch):
|
||||
async def fake_page(stream, page=1, limit=50):
|
||||
assert page == 1
|
||||
totals = {"issue": 84, "filed": 62, "pull": 61, "review": 73}
|
||||
totals = {"issue": 84, "filed": 62, "pull": 61, "review": 73, "authored": 12}
|
||||
return {
|
||||
"items": [], "page": 1, "total": totals[stream],
|
||||
"has_more": True, "stream": stream,
|
||||
@@ -646,6 +672,7 @@ async def test_initial_work_collections_expose_independent_pagination(monkeypatc
|
||||
assert pulls.pagination == {
|
||||
"pull": {"page": 1, "total": 61, "has_more": True},
|
||||
"review": {"page": 1, "total": 73, "has_more": True},
|
||||
"authored": {"page": 1, "total": 12, "has_more": True},
|
||||
}
|
||||
|
||||
|
||||
@@ -666,11 +693,12 @@ async def test_work_collections_include_supported_review_request_search(monkeypa
|
||||
("filed", 1, 50),
|
||||
("pull", 1, 50),
|
||||
("review", 1, 50),
|
||||
("authored", 1, 50),
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pull_requests_merge_assignment_and_review_responsibilities(monkeypatch):
|
||||
async def test_pull_requests_merge_assignment_review_and_authored_responsibilities(monkeypatch):
|
||||
assigned = {
|
||||
"id": 11,
|
||||
"number": 7,
|
||||
@@ -683,10 +711,24 @@ async def test_pull_requests_merge_assignment_and_review_responsibilities(monkey
|
||||
"title": "Review mobile",
|
||||
"repository": {"full_name": "stackchain/mobile"},
|
||||
}
|
||||
authored_only = {
|
||||
"id": 13,
|
||||
"number": 9,
|
||||
"title": "Ship authored flow",
|
||||
"repository": {"full_name": "stackchain/dashboard"},
|
||||
}
|
||||
|
||||
async def fake_page(stream, page=1, limit=50):
|
||||
items = [assigned] if stream == "pull" else [assigned.copy(), review_only]
|
||||
reason = "assigned_to_me" if stream == "pull" else "review_requested"
|
||||
items = {
|
||||
"pull": [assigned],
|
||||
"review": [assigned.copy(), review_only],
|
||||
"authored": [assigned.copy(), authored_only],
|
||||
}[stream]
|
||||
reason = {
|
||||
"pull": "assigned_to_me",
|
||||
"review": "review_requested",
|
||||
"authored": "authored_by_me",
|
||||
}[stream]
|
||||
return {
|
||||
"stream": stream,
|
||||
"items": [{**item, "work_reasons": [reason]} for item in items],
|
||||
@@ -697,9 +739,44 @@ async def test_pull_requests_merge_assignment_and_review_responsibilities(monkey
|
||||
|
||||
pulls = await gitea_proxy.pull_requests()
|
||||
|
||||
assert [pull["id"] for pull in pulls] == [11, 12]
|
||||
assert pulls[0]["work_reasons"] == ["assigned_to_me", "review_requested"]
|
||||
assert [pull["id"] for pull in pulls] == [11, 12, 13]
|
||||
assert pulls[0]["work_reasons"] == [
|
||||
"assigned_to_me", "review_requested", "authored_by_me",
|
||||
]
|
||||
assert pulls[1]["work_reasons"] == ["review_requested"]
|
||||
assert pulls[2]["work_reasons"] == ["authored_by_me"]
|
||||
assert pulls.pagination["authored"] == {
|
||||
"page": 1, "total": 2, "has_more": False,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_authored_pull_failure_keeps_other_pull_work_and_marks_only_that_stream_unavailable(monkeypatch):
|
||||
async def fake_page(stream, page=1, limit=50):
|
||||
if stream == "authored":
|
||||
raise httpx.ConnectError("authored search unavailable")
|
||||
item = {
|
||||
"id": 11 if stream == "pull" else 12,
|
||||
"number": 7 if stream == "pull" else 8,
|
||||
"title": "Assigned" if stream == "pull" else "Review",
|
||||
"repository": {"full_name": "stackchain/dashboard"},
|
||||
"work_reasons": ["assigned_to_me" if stream == "pull" else "review_requested"],
|
||||
}
|
||||
return {
|
||||
"stream": stream, "items": [item], "page": page,
|
||||
"total": 1, "has_more": False,
|
||||
}
|
||||
|
||||
monkeypatch.setattr(gitea_proxy, "work_page", fake_page)
|
||||
|
||||
pulls = await gitea_proxy.pull_requests()
|
||||
|
||||
assert [pull["id"] for pull in pulls] == [11, 12]
|
||||
assert pulls.pagination["pull"].get("unavailable", False) is False
|
||||
assert pulls.pagination["review"].get("unavailable", False) is False
|
||||
assert pulls.pagination["authored"] == {
|
||||
"page": 1, "total": 0, "has_more": False, "unavailable": True,
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -875,6 +875,108 @@ async def test_work_preview_marks_authoritative_requested_pull_review_actionable
|
||||
assert "/api/v1/repos/stackchain/web/pulls/9" in requested_paths
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_work_preview_offers_closed_authored_unmerged_pull_recovery_with_head_guard():
|
||||
requested_paths = []
|
||||
|
||||
async def handler(request):
|
||||
requested_paths.append(request.url.path)
|
||||
if request.url.path.endswith("/user"):
|
||||
return httpx.Response(200, json={"login": "timmy"})
|
||||
if request.url.path.endswith("/pulls/9"):
|
||||
return httpx.Response(200, json={
|
||||
"number": 9,
|
||||
"state": "closed",
|
||||
"merged": False,
|
||||
"user": {"login": "timmy"},
|
||||
"head": {"sha": "abc1234"},
|
||||
"requested_reviewers": [],
|
||||
})
|
||||
return httpx.Response(200, json={
|
||||
"number": 9,
|
||||
"title": "Recover mobile flow",
|
||||
"state": "closed",
|
||||
"html_url": "http://127.0.0.1:3000/stackchain/web/pulls/9",
|
||||
"user": {"login": "timmy"},
|
||||
"pull_request": {"merged": False},
|
||||
"assignees": [],
|
||||
})
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
preview = await gitea_proxy.work_preview("stackchain/web", "pull", 9)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert preview["authored_pull_reopenable"] is True
|
||||
assert preview["head_sha"] == "abc1234"
|
||||
assert "/api/v1/repos/stackchain/web/pulls/9" in requested_paths
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_work_preview_does_not_offer_closed_pull_recovery_to_non_author():
|
||||
async def handler(request):
|
||||
if request.url.path.endswith("/user"):
|
||||
return httpx.Response(200, json={"login": "timmy"})
|
||||
if request.url.path.endswith("/pulls/9"):
|
||||
return httpx.Response(200, json={
|
||||
"number": 9,
|
||||
"state": "closed",
|
||||
"merged": False,
|
||||
"user": {"login": "alexander"},
|
||||
"head": {"sha": "abc1234"},
|
||||
})
|
||||
return httpx.Response(200, json={
|
||||
"number": 9,
|
||||
"title": "Foreign pull",
|
||||
"state": "closed",
|
||||
"html_url": "http://127.0.0.1:3000/stackchain/web/pulls/9",
|
||||
"user": {"login": "alexander"},
|
||||
"pull_request": {"merged": False},
|
||||
"assignees": [],
|
||||
})
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
preview = await gitea_proxy.work_preview("stackchain/web", "pull", 9)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert preview["authored_pull_reopenable"] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_work_preview_does_not_offer_recovery_for_merged_pull():
|
||||
async def handler(request):
|
||||
if request.url.path.endswith("/user"):
|
||||
return httpx.Response(200, json={"login": "timmy"})
|
||||
if request.url.path.endswith("/pulls/9"):
|
||||
return httpx.Response(200, json={
|
||||
"number": 9,
|
||||
"state": "closed",
|
||||
"merged": True,
|
||||
"user": {"login": "timmy"},
|
||||
"head": {"sha": "abc1234"},
|
||||
})
|
||||
return httpx.Response(200, json={
|
||||
"number": 9,
|
||||
"title": "Merged pull",
|
||||
"state": "closed",
|
||||
"html_url": "http://127.0.0.1:3000/stackchain/web/pulls/9",
|
||||
"user": {"login": "timmy"},
|
||||
"pull_request": {"merged": True},
|
||||
"assignees": [],
|
||||
})
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(handler))
|
||||
try:
|
||||
preview = await gitea_proxy.work_preview("stackchain/web", "pull", 9)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert preview["authored_pull_reopenable"] is False
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_work_preview_offers_reopen_only_for_closed_issues():
|
||||
async def handler(request):
|
||||
|
||||
@@ -435,5 +435,5 @@ async def test_dashboard_syncs_every_later_change_and_exposes_account_status():
|
||||
def test_later_sync_ships_atomically_in_the_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/later-sync.js'" in source
|
||||
@@ -54,7 +54,7 @@ process.stdout.write(JSON.stringify({{ status: status.textContent }}));
|
||||
)
|
||||
|
||||
assert json.loads(result.stdout)["status"] == (
|
||||
"Stackchain locked after inactivity. Your drafts and queued work are still "
|
||||
"Stackchain locked. Your drafts and queued work are still "
|
||||
"on this device. Sign in to resume."
|
||||
)
|
||||
|
||||
|
||||
@@ -256,4 +256,4 @@ def test_markdown_work_bodies_are_mobile_safe_block_containers():
|
||||
assert ".markdown-content { min-width:0; max-width:100%; overflow-wrap:anywhere;" in css
|
||||
assert ".markdown-content pre { max-width:100%; overflow-x:auto;" in css
|
||||
assert ".markdown-content a { min-height:44px;" in css
|
||||
assert "stackchain-dashboard-shell-v138" in worker
|
||||
assert "stackchain-dashboard-shell-v139" in worker
|
||||
@@ -45,7 +45,7 @@ def test_offline_shell_contains_every_local_dashboard_runtime_asset():
|
||||
shell_assets = set(re.findall(r"BASE \+ '([^']+)'", worker.split("async function sessionCsrf", 1)[0]))
|
||||
|
||||
assert local_assets <= shell_assets, f"Offline shell is missing: {sorted(local_assets - shell_assets)}"
|
||||
assert "stackchain-dashboard-shell-v138" in worker
|
||||
assert "stackchain-dashboard-shell-v139" in worker
|
||||
|
||||
|
||||
def test_all_conversation_composers_offer_accessible_mobile_mentions():
|
||||
|
||||
@@ -383,7 +383,7 @@ def test_mobile_dashboard_mounts_phone_safe_device_setup_flow():
|
||||
assert "controller.recoverPermission('deadline')" in dashboard
|
||||
assert "pushControllerReady.then(ensureDeviceSetup)" in dashboard
|
||||
assert "BASE + 'static/mobile-device-setup.js'" in worker
|
||||
assert "stackchain-dashboard-shell-v138" in worker
|
||||
assert "stackchain-dashboard-shell-v139" in worker
|
||||
assert ".device-setup-panel" in css
|
||||
assert ".device-readiness-card" in css
|
||||
assert "overflow-x:hidden" in css
|
||||
|
||||
@@ -133,6 +133,37 @@ process.stdout.write(JSON.stringify({{current:controller.current(),hash:location
|
||||
}
|
||||
|
||||
|
||||
def test_late_inactive_route_event_does_not_release_background_owned_by_next_overlay():
|
||||
script = f"""
|
||||
const createInsights = require({json.dumps(str(CONTROLLER))});
|
||||
const listeners = {{}};
|
||||
const element = () => ({{
|
||||
hidden:false, inert:false, attributes:{{}}, focuses:0, listeners:{{}},
|
||||
setAttribute(name,value) {{ this.attributes[name] = String(value); }},
|
||||
removeAttribute(name) {{ delete this.attributes[name]; }},
|
||||
addEventListener(name,fn) {{ this.listeners[name] = fn; }},
|
||||
focus() {{ this.focuses += 1; }},
|
||||
}});
|
||||
const root=element(), launcher=element(), closeButton=element(), dock=element(), hud=element(), header=element();
|
||||
const location={{pathname:'/dashboard/', search:'', hash:'#/insights'}};
|
||||
const history={{state:null, pushState() {{}}, back() {{}}, replaceState(state,unused,url) {{
|
||||
this.state=state; location.hash=url.slice(url.indexOf('#'));
|
||||
}}}};
|
||||
const controller=createInsights({{
|
||||
root,launcher,closeButton,dock,hud,backgrounds:[header],history,location,
|
||||
eventTarget:{{addEventListener(name,fn) {{ listeners[name]=fn; }}}},
|
||||
mediaQuery:{{matches:true,addEventListener() {{}}}},
|
||||
}});
|
||||
controller.start();
|
||||
closeButton.listeners.click();
|
||||
header.inert = true;
|
||||
listeners.hashchange();
|
||||
process.stdout.write(JSON.stringify({{current:controller.current(), headerInert:header.inert}}));
|
||||
"""
|
||||
|
||||
assert run_node(script) == {"current": False, "headerInert": True}
|
||||
|
||||
|
||||
def test_escape_requests_back_navigation_only_while_insights_is_open():
|
||||
script = f"""
|
||||
const createInsights=require({json.dumps(str(CONTROLLER))});
|
||||
@@ -243,5 +274,5 @@ async def test_mobile_home_progressively_discloses_secondary_panels_as_insights(
|
||||
def test_mobile_insights_rolls_into_the_offline_shell():
|
||||
worker = (CONTROLLER.parent / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in worker
|
||||
assert "stackchain-dashboard-shell-v139" in worker
|
||||
assert "BASE + 'static/mobile-insights.js'" in worker
|
||||
@@ -414,7 +414,7 @@ async def test_dashboard_wires_thumb_safe_start_day_briefing_into_offline_mobile
|
||||
assert ".mobile-start-day-finish { min-height:44px;" in html
|
||||
assert "max-width:100%; overflow-wrap:anywhere;" in html
|
||||
assert "BASE + 'static/mobile-start-day.js'" in service_worker
|
||||
assert "stackchain-dashboard-shell-v138" in service_worker
|
||||
assert "stackchain-dashboard-shell-v139" in service_worker
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
+430
-4
@@ -100,6 +100,100 @@ process.stdout.write(JSON.stringify(buildMyWork({json.dumps(payload)})));
|
||||
assert result[1]["reason"] == "Filed by you"
|
||||
|
||||
|
||||
def test_authored_pull_is_classified_for_the_my_prs_queue():
|
||||
payload = {
|
||||
"user": {"login": "timmy"},
|
||||
"pull_requests": [{
|
||||
"number": 41, "title": "Ship mobile flow", "repository": "stackchain/dashboard",
|
||||
"state": "open", "user": "timmy", "assignees": [],
|
||||
"work_reasons": ["authored_by_me"], "updated_at": "2026-08-24T12:00:00Z",
|
||||
}],
|
||||
}
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
process.stdout.write(JSON.stringify(buildMyWork({json.dumps(payload)})));
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
result = json.loads(completed.stdout)
|
||||
assert result[0]["is_authored"] is True
|
||||
assert result[0]["reason"] == "Authored by you"
|
||||
assert result[0]["kind"] == "pull"
|
||||
|
||||
|
||||
def test_authored_pull_branch_update_is_single_flight_and_head_guarded():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const calls = [];
|
||||
let resolve;
|
||||
const pending = new Promise(done => {{ resolve = done; }});
|
||||
const controller = createPullSheet({{
|
||||
fetchJson:(url, options) => {{ calls.push([url, options]); return pending; }},
|
||||
storage:{{}},
|
||||
}});
|
||||
const item = {{repository:'stackchain/api', number:7}};
|
||||
const first = controller.updateBranch(item, 'abc1234');
|
||||
const second = controller.updateBranch(item, 'abc1234');
|
||||
resolve({{previous_head_sha:'abc1234', head_sha:'def5678'}});
|
||||
Promise.all([first, second]).then(results => process.stdout.write(JSON.stringify({{
|
||||
same:first === second,
|
||||
calls:calls.map(([url, options]) => [url, options.method, JSON.parse(options.body)]),
|
||||
heads:results.map(result => result.head_sha),
|
||||
}}))).catch(error => {{ console.error(error); process.exit(1); }});
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], text=True, capture_output=True)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
assert json.loads(completed.stdout) == {
|
||||
"same": True,
|
||||
"calls": [[
|
||||
"api/v1/repos/stackchain/api/pulls/7/update-branch",
|
||||
"POST",
|
||||
{"expected_head_sha": "abc1234"},
|
||||
]],
|
||||
"heads": ["def5678", "def5678"],
|
||||
}
|
||||
|
||||
|
||||
def test_mobile_pull_review_exposes_update_branch_recovery():
|
||||
frontend = Path(__file__).parents[1] / "frontend"
|
||||
html = (frontend / "index.html").read_text()
|
||||
source = PULL_SHEET.read_text()
|
||||
css = (frontend / "dashboard.css").read_text()
|
||||
|
||||
assert 'id="update-pull-branch"' in html
|
||||
assert 'id="pull-branch-update-status"' in html
|
||||
assert "controller.updateBranch(item, detail.head_sha)" in source
|
||||
assert "doc.querySelector('#pull-review-retry')?.click()" in source
|
||||
assert ".pull-branch-update button" in css and "min-height:44px" in css
|
||||
|
||||
|
||||
def test_my_prs_filter_and_count_include_only_authored_pulls():
|
||||
script = f"""
|
||||
const buildMyWork = require({json.dumps(str(MY_WORK))});
|
||||
const items = buildMyWork({{
|
||||
user:{{login:'timmy'}},
|
||||
pull_requests:[
|
||||
{{number:41,title:'Authored',repository:'stackchain/dashboard',state:'open',user:'timmy',
|
||||
assignees:[],work_reasons:['authored_by_me']}},
|
||||
{{number:42,title:'Review',repository:'stackchain/dashboard',state:'open',user:'alex',
|
||||
assignees:[],work_reasons:['review_requested']}},
|
||||
],
|
||||
}});
|
||||
process.stdout.write(JSON.stringify({{
|
||||
authored:buildMyWork.filterMyWork(items,'authored').map(item=>item.number),
|
||||
counts:buildMyWork.countMyWork(items),
|
||||
}}));
|
||||
"""
|
||||
completed = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert completed.returncode == 0, completed.stderr
|
||||
result = json.loads(completed.stdout)
|
||||
assert result["authored"] == [41]
|
||||
assert result["counts"]["authored"] == 1
|
||||
|
||||
|
||||
def test_completed_child_resolves_only_a_canonical_reciprocal_parent_task():
|
||||
script = f"""
|
||||
const sheet = require({json.dumps(str(ISSUE_SHEET))});
|
||||
@@ -1059,6 +1153,24 @@ async def test_agenda_activation_checks_all_issue_pages_before_showing_empty_sta
|
||||
assert "selectedWorkFilter === 'agenda' && workPagination.issue?.has_more" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_my_prs_is_a_thumb_safe_mobile_queue_and_desktop_filter():
|
||||
html = await dashboard()
|
||||
markup = (Path(__file__).resolve().parents[1] / "frontend" / "index.html").read_text()
|
||||
css = (Path(__file__).resolve().parents[1] / "frontend" / "dashboard.css").read_text()
|
||||
|
||||
assert 'data-work-filter="authored"' in markup
|
||||
assert 'data-work-count="authored"' in markup
|
||||
assert 'data-mobile-queue="authored"' in markup
|
||||
assert 'data-mobile-queue-count="authored"' in markup
|
||||
assert '<strong>My PRs</strong>' in markup
|
||||
assert ".mobile-queue-list button" in css and "min-height:56px" in css
|
||||
assert "['all', 'today', 'agenda', 'attention', 'filed', 'authored'" in html
|
||||
assert "['issue', 'pull', 'review', 'authored'].includes(selectedWorkFilter)" in html
|
||||
assert "authored: 'pull requests'" in html
|
||||
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_queue_finder_is_labeled_thumb_safe_and_offers_older_search():
|
||||
html = await dashboard()
|
||||
@@ -4988,7 +5100,8 @@ process.stdout.write(JSON.stringify(buildMyWork.countMyWork({json.dumps(items)})
|
||||
)
|
||||
|
||||
assert json.loads(result.stdout) == {
|
||||
"all": 3, "attention": 1, "filed": 0, "issue": 1, "pull": 1, "review": 1, "update": 0
|
||||
"all": 3, "attention": 1, "filed": 0, "authored": 0,
|
||||
"issue": 1, "pull": 1, "review": 1, "update": 0
|
||||
}
|
||||
|
||||
|
||||
@@ -6165,7 +6278,8 @@ process.stdout.write(JSON.stringify({{
|
||||
assert output["updates"][1]["kind"] == "update"
|
||||
assert output["updates"][1]["update_reason"] == ""
|
||||
assert output["counts"] == {
|
||||
"all": 2, "attention": 2, "filed": 0, "issue": 1, "pull": 0, "review": 0, "update": 2
|
||||
"all": 2, "attention": 2, "filed": 0, "authored": 0,
|
||||
"issue": 1, "pull": 0, "review": 0, "update": 2
|
||||
}
|
||||
assert output["summary"] == "2 unread updates · 0 reviews · 1 assigned"
|
||||
|
||||
@@ -7575,6 +7689,39 @@ process.stdout.write(JSON.stringify({{
|
||||
assert output["released"] == "stackchain/api#7 released. Choose the next ready Today item."
|
||||
|
||||
|
||||
def test_authored_unassigned_pull_hides_assignment_ownership_controls():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const elements = new Map([
|
||||
['#pull-ownership', {{open:true,hidden:false,inert:false}}],
|
||||
['#pull-handoff-recipient', {{innerHTML:'stale',disabled:false}}],
|
||||
['#confirm-pull-handoff', {{disabled:false,textContent:''}}],
|
||||
['#load-pull-handoff', {{disabled:false}}],
|
||||
['#release-pull', {{disabled:false,textContent:''}}],
|
||||
['#pull-handoff-status', {{textContent:''}}],
|
||||
['#edit-pull-content', {{hidden:false}}],
|
||||
['#pull-edit-form', {{hidden:false}}],
|
||||
['#pull-edit-status', {{textContent:'stale'}}],
|
||||
]);
|
||||
const doc = {{querySelector:selector => elements.get(selector)}};
|
||||
createPullSheet.resetOwnershipControls(
|
||||
doc,
|
||||
{{key:'stackchain/api#7'}},
|
||||
() => false,
|
||||
{{authored:true,assigned:false}}
|
||||
);
|
||||
process.stdout.write(JSON.stringify(Object.fromEntries(elements)));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["#pull-ownership"]["hidden"] is True
|
||||
assert output["#pull-ownership"]["inert"] is True
|
||||
assert output["#load-pull-handoff"]["disabled"] is True
|
||||
assert output["#release-pull"]["disabled"] is True
|
||||
|
||||
|
||||
def test_pull_sheet_single_flights_handoff_and_release_ownership_mutations():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
@@ -7629,6 +7776,8 @@ const controller = createPullSheet({{
|
||||
return new Promise(resolve => {{ finish = resolve; }});
|
||||
}}
|
||||
}});
|
||||
const notified = [];
|
||||
controller.onReviewRequested = result => notified.push(result);
|
||||
const item = {{repository:'stackchain/api',number:7}};
|
||||
(async () => {{
|
||||
const candidates = await controller.loadReviewCandidates(item);
|
||||
@@ -7636,7 +7785,7 @@ const item = {{repository:'stackchain/api',number:7}};
|
||||
const duplicate = controller.requestReview(item, 'casey', 'abc1234');
|
||||
finish({{reviewer:'casey',requested_reviewers:['sam','casey']}});
|
||||
const results = await Promise.all([first, duplicate]);
|
||||
process.stdout.write(JSON.stringify({{calls,candidates,results,same:first===duplicate}}));
|
||||
process.stdout.write(JSON.stringify({{calls,candidates,results,same:first===duplicate,notified}}));
|
||||
}})();
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
@@ -7656,6 +7805,46 @@ const item = {{repository:'stackchain/api',number:7}};
|
||||
{"reviewer": "casey", "requested_reviewers": ["sam", "casey"]},
|
||||
],
|
||||
"same": True,
|
||||
"notified": [{"reviewer": "casey", "requested_reviewers": ["sam", "casey"]}],
|
||||
}
|
||||
|
||||
|
||||
def test_pull_sheet_single_flights_pending_review_cancellation():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const calls = [];
|
||||
let finish;
|
||||
const controller = createPullSheet({{
|
||||
storage:null,
|
||||
fetchJson:(url, options={{}}) => {{
|
||||
calls.push({{url, method:options.method, body:JSON.parse(options.body)}});
|
||||
return new Promise(resolve => {{ finish = resolve; }});
|
||||
}}
|
||||
}});
|
||||
const notified = [];
|
||||
controller.onReviewCancelled = result => notified.push(result);
|
||||
const item = {{repository:'stackchain/api',number:7}};
|
||||
(async () => {{
|
||||
const first = controller.cancelReview(item, 'sam', 'abc1234');
|
||||
const duplicate = controller.cancelReview(item, 'sam', 'abc1234');
|
||||
finish({{reviewer:'sam',head_sha:'abc1234',requested_reviewers:['casey']}});
|
||||
const results = await Promise.all([first, duplicate]);
|
||||
process.stdout.write(JSON.stringify({{calls,results,same:first===duplicate,notified}}));
|
||||
}})();
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output == {
|
||||
"calls": [{
|
||||
"url": "api/v1/repos/stackchain/api/pulls/7/request-review",
|
||||
"method": "DELETE",
|
||||
"body": {"reviewer": "sam", "expected_head_sha": "abc1234"},
|
||||
}],
|
||||
"results": [{"reviewer": "sam", "head_sha": "abc1234", "requested_reviewers": ["casey"]}] * 2,
|
||||
"same": True,
|
||||
"notified": [{"reviewer": "sam", "head_sha": "abc1234", "requested_reviewers": ["casey"]}],
|
||||
}
|
||||
|
||||
|
||||
@@ -7675,6 +7864,22 @@ def test_pull_sheet_exposes_touch_safe_review_request_flow():
|
||||
assert "pullController.setReviewDetail(detail)" in dashboard
|
||||
|
||||
|
||||
def test_pull_sheet_exposes_mobile_reviewer_status_and_updated_review_action():
|
||||
root = PULL_SHEET.parents[1]
|
||||
html = (root / "frontend" / "index.html").read_text()
|
||||
css = (root / "frontend" / "dashboard.css").read_text()
|
||||
dashboard = (root / "frontend" / "dashboard.js").read_text()
|
||||
|
||||
assert 'id="pull-reviewer-statuses"' in html
|
||||
assert 'id="request-updated-pull-review"' in html
|
||||
assert 'id="pull-reviewer-status" class="small" aria-live="polite"' in html
|
||||
assert ".pull-reviewer-status" in css
|
||||
assert "overflow-wrap:anywhere" in css
|
||||
assert "#request-updated-pull-review { min-height:44px;" in css
|
||||
assert "createPullSheet.review(detail, pullReviewState, document)" in dashboard
|
||||
assert "reviewers.some(reviewer => reviewer.status === 'outdated')" in PULL_SHEET.read_text()
|
||||
|
||||
|
||||
def test_pull_sheet_surfaces_pending_merge_confirmation_guidance():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
@@ -7721,6 +7926,126 @@ process.stdout.write(JSON.stringify(states.map(createPullSheet.mergeEligibility)
|
||||
assert output[3]["allowed"] is False and "conflict" in output[3]["reason"].lower()
|
||||
|
||||
|
||||
def test_pull_sheet_renders_reviewer_decisions_and_blocks_unresolved_requests():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const base = {{state:'open', draft:false, mergeable:true, merged:false, ci_state:'success', head_sha:'new'}};
|
||||
const states = [
|
||||
[{{login:'casey', status:'waiting', head_sha:'new', blocking:true}}],
|
||||
[{{login:'sam', status:'changes_requested', head_sha:'new', blocking:true}}],
|
||||
[{{login:'lee', status:'outdated', head_sha:'old', blocking:true}}],
|
||||
[{{login:'pat', status:'approved', head_sha:'new', blocking:false}}],
|
||||
];
|
||||
process.stdout.write(JSON.stringify({{
|
||||
eligibility:states.map(reviewers => createPullSheet.mergeEligibility({{...base, reviewers}})),
|
||||
html:createPullSheet.renderReviewerStatuses(states.flat(), value => String(value)
|
||||
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')),
|
||||
}}));
|
||||
"""
|
||||
output = json.loads(subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
).stdout)
|
||||
|
||||
assert output["eligibility"] == [
|
||||
{"allowed": False, "reason": "Waiting for @casey’s review"},
|
||||
{"allowed": False, "reason": "@sam requested changes"},
|
||||
{"allowed": False, "reason": "@lee’s review is outdated after new commits"},
|
||||
{"allowed": True, "reason": "Ready to merge"},
|
||||
]
|
||||
assert "@casey" in output["html"] and "Waiting for review" in output["html"]
|
||||
assert "Changes requested" in output["html"]
|
||||
assert "Outdated after new commits" in output["html"]
|
||||
assert "Approved current head" in output["html"]
|
||||
|
||||
|
||||
def test_pull_sheet_offers_cancel_only_for_pending_review_requests():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const html = createPullSheet.renderReviewerStatuses([
|
||||
{{login:'sam',status:'waiting'}},
|
||||
{{login:'casey',status:'approved'}},
|
||||
{{login:'lee',status:'commented'}},
|
||||
], value => String(value));
|
||||
process.stdout.write(html);
|
||||
"""
|
||||
html = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True).stdout
|
||||
|
||||
assert html.count('data-cancel-review-request=') == 1
|
||||
assert 'data-cancel-review-request="sam"' in html
|
||||
assert "Cancel request" in html
|
||||
assert 'data-cancel-review-request="casey"' not in html
|
||||
assert 'data-cancel-review-request="lee"' not in html
|
||||
|
||||
|
||||
def test_pull_sheet_pending_review_cancellation_is_touch_safe_and_opens_replacement_picker():
|
||||
root = PULL_SHEET.parents[1]
|
||||
css = (root / "frontend" / "dashboard.css").read_text()
|
||||
script = PULL_SHEET.read_text()
|
||||
|
||||
assert ".cancel-review-request { min-height:44px;" in css
|
||||
assert "controller.cancelReview(selected, reviewer, detail.head_sha)" in script
|
||||
assert "Choose a replacement reviewer." in script
|
||||
assert "qs('#pull-review-request').open = true" in script
|
||||
|
||||
|
||||
def test_pull_sheet_renders_bounded_feedback_grouped_by_file():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const html = createPullSheet.renderReviewerStatuses([{{
|
||||
login:'sam', status:'changes_requested', head_sha:'abc123', blocking:true,
|
||||
summary:'Please <split> this helper.',
|
||||
comments:[
|
||||
{{path:'src/api.py', body:'Handle <empty>.', line:12}},
|
||||
{{path:'src/api.py', body:'Keep the return explicit.'}},
|
||||
{{path:'frontend/app.js', body:'Show the error.'}},
|
||||
],
|
||||
}}], value => String(value).replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>'));
|
||||
process.stdout.write(html);
|
||||
"""
|
||||
html = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True).stdout
|
||||
|
||||
assert "Review feedback" in html
|
||||
assert "Please <split> this helper." in html
|
||||
assert html.count('data-review-feedback-file="src/api.py"') == 1
|
||||
assert 'data-review-feedback-file="frontend/app.js"' in html
|
||||
assert "Handle <empty>." in html
|
||||
assert "Line 12" in html
|
||||
assert "View in changes" in html
|
||||
assert "Please <split>" not in html
|
||||
|
||||
|
||||
def test_pull_sheet_marks_inline_feedback_as_on_demand_and_retryable():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const render = state => createPullSheet.renderReviewerStatuses([{{
|
||||
login:'sam', review_id:8, status:'changes_requested', head_sha:'abc1234',
|
||||
blocking:true, summary:'Please fix this.', feedback_state:state,
|
||||
}}], value => String(value));
|
||||
process.stdout.write(JSON.stringify({{idle:render(undefined), failed:render('error')}}));
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], check=True, capture_output=True, text=True)
|
||||
output = json.loads(result.stdout)
|
||||
|
||||
assert "Load inline feedback" in output["idle"]
|
||||
assert 'data-load-review-feedback="8"' in output["idle"]
|
||||
assert "Feedback unavailable" in output["failed"]
|
||||
assert "Retry feedback" in output["failed"]
|
||||
assert "Address feedback" not in output["idle"]
|
||||
|
||||
|
||||
def test_pull_sheet_binds_on_demand_feedback_with_visible_retry_state():
|
||||
script = PULL_SHEET.read_text()
|
||||
|
||||
assert "event.target.closest?.('[data-load-review-feedback]')" in script
|
||||
assert "await controller.loadFeedback(item, detail, reviewer" in script
|
||||
assert "reviewer.feedback_state = 'loading'" in script
|
||||
assert "reviewer.feedback_state = 'loaded'" in script
|
||||
assert "reviewer.feedback_state = 'error'" in script
|
||||
assert "result.head_sha !== detail.head_sha" in script
|
||||
css = (Path(__file__).parents[1] / "frontend" / "dashboard.css").read_text()
|
||||
assert "[data-load-review-feedback] { min-height:44px; width:100%;" in css
|
||||
|
||||
|
||||
def test_pull_sheet_persists_head_scoped_file_review_and_gates_merge():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
@@ -7796,6 +8121,37 @@ Promise.allSettled([first, concurrent]).then(async failed => {{
|
||||
]
|
||||
|
||||
|
||||
def test_pull_sheet_feedback_is_single_flight_cached_by_head_and_review():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const calls = [];
|
||||
let resolveFeedback;
|
||||
const sheet = createPullSheet({{storage:null, fetchJson:url => {{
|
||||
calls.push(url);
|
||||
return new Promise(resolve => {{ resolveFeedback = resolve; }});
|
||||
}}}});
|
||||
const item = {{repository:'stackchain/api', number:7}};
|
||||
const detail = {{head_sha:'abc1234'}};
|
||||
const reviewer = {{review_id:8, head_sha:'abc1234'}};
|
||||
const first = sheet.loadFeedback(item, detail, reviewer);
|
||||
const concurrent = sheet.loadFeedback(item, detail, reviewer);
|
||||
resolveFeedback({{review_id:8, head_sha:'abc1234', reviewed_head_sha:'abc1234', comments:[{{id:99}}]}});
|
||||
Promise.all([first, concurrent]).then(async results => {{
|
||||
const cached = await sheet.loadFeedback(item, detail, reviewer);
|
||||
process.stdout.write(JSON.stringify({{same:first === concurrent, results, cached, calls}}));
|
||||
}});
|
||||
"""
|
||||
result = subprocess.run(["node", "-e", script], capture_output=True, text=True)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
output = json.loads(result.stdout)
|
||||
assert output["same"] is True
|
||||
assert output["cached"] == output["results"][0]
|
||||
assert output["calls"] == [
|
||||
"api/v1/repos/stackchain/api/pulls/7/reviews/8/feedback?expected_head_sha=abc1234"
|
||||
]
|
||||
|
||||
|
||||
def test_pull_sheet_refreshes_status_only_without_clearing_review_progress():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
@@ -8271,7 +8627,7 @@ async def test_mobile_filters_wrap_show_counts_and_persist_for_the_session():
|
||||
assert 'data-work-count="review"' in html
|
||||
assert 'data-work-count="update"' in html
|
||||
assert 'data-work-count="later"' in html
|
||||
assert "['all', 'today', 'agenda', 'attention', 'filed', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)" in html
|
||||
assert "['all', 'today', 'agenda', 'attention', 'filed', 'authored', 'issue', 'pull', 'review', 'update', 'later', 'draft'].includes(savedFilter)" in html
|
||||
assert 'data-work-count="draft"' in html
|
||||
assert 'sessionStorage.getItem(WORK_FILTER_KEY)' in html
|
||||
assert 'sessionStorage.setItem(WORK_FILTER_KEY, selectedWorkFilter)' in html
|
||||
@@ -8394,6 +8750,76 @@ process.stdout.write(JSON.stringify({{result, offline}}));
|
||||
assert output["offline"]["summary"].startswith("Last known · ")
|
||||
|
||||
|
||||
def test_failed_actions_check_renders_in_app_recovery_control_only_when_supported():
|
||||
script = f"""
|
||||
const reviewSheet = require({json.dumps(str(REVIEW_SHEET))});
|
||||
const escapeHtml = value => String(value)
|
||||
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"');
|
||||
const supported = reviewSheet.renderChecks([
|
||||
{{name:'CI / lint', state:'failure', url:'https://forge.example/jobs/3', recovery:{{run_id:91, job_index:3}}}},
|
||||
], escapeHtml);
|
||||
const external = reviewSheet.renderChecks([
|
||||
{{name:'Vendor scan', state:'failure', url:'https://forge.example/jobs/4'}},
|
||||
], escapeHtml);
|
||||
process.stdout.write(JSON.stringify({{supported, external}}));
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
)
|
||||
output = json.loads(result.stdout)
|
||||
|
||||
assert 'class="ci-check-inspect"' in output["supported"]["html"]
|
||||
assert 'data-run-id="91"' in output["supported"]["html"]
|
||||
assert 'data-job-index="3"' in output["supported"]["html"]
|
||||
assert "Inspect failure" in output["supported"]["html"]
|
||||
assert "ci-check-inspect" not in output["external"]["html"]
|
||||
assert "Open job" in output["external"]["html"]
|
||||
|
||||
|
||||
def test_pull_controller_loads_failure_and_retries_exact_head():
|
||||
script = f"""
|
||||
const createPullSheet = require({json.dumps(str(PULL_SHEET))});
|
||||
const calls = [];
|
||||
const controller = createPullSheet({{
|
||||
fetchJson: async (url, options) => {{ calls.push({{url, options}}); return {{status:'queued'}}; }},
|
||||
storage: null,
|
||||
}});
|
||||
const item = {{repository:'stackchain/api', number:7}};
|
||||
controller.loadCheckFailure(item, 'abc1234', 91, 3).then(() =>
|
||||
controller.retryCheck(item, 'abc1234', 91, 3)
|
||||
).then(() => process.stdout.write(JSON.stringify(calls)));
|
||||
"""
|
||||
result = subprocess.run(
|
||||
["node", "-e", script], check=True, capture_output=True, text=True
|
||||
)
|
||||
calls = json.loads(result.stdout)
|
||||
|
||||
assert calls[0]["url"].endswith(
|
||||
"/pulls/7/checks/91/jobs/3/failure?expected_head_sha=abc1234"
|
||||
)
|
||||
assert calls[0]["options"]["headers"]["Accept"] == "application/json"
|
||||
assert calls[1]["url"].endswith("/pulls/7/checks/91/jobs/3/retry")
|
||||
assert calls[1]["options"]["method"] == "POST"
|
||||
assert json.loads(calls[1]["options"]["body"]) == {"expected_head_sha": "abc1234"}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_pull_workspace_packages_accessible_ci_recovery_panel():
|
||||
html = await dashboard()
|
||||
|
||||
assert 'id="pull-check-recovery"' in html
|
||||
assert 'id="pull-check-recovery-title"' in html
|
||||
assert 'id="pull-check-log"' in html
|
||||
assert 'id="retry-pull-check"' in html
|
||||
assert 'id="close-pull-check-recovery"' in html
|
||||
assert 'aria-live="assertive"' in html
|
||||
assert "createPullSheet.bindOwnershipControls" in html
|
||||
assert "#pull-check-list" in html and "ci-check-inspect" in html
|
||||
assert ".ci-check-recovery" in html and "max-width:100%" in html
|
||||
assert ".ci-check-log" in html and "overflow-x:auto" in html
|
||||
assert ".ci-check-actions" in html and "min-height:44px" in html
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_mobile_pull_review_sheets_refresh_checks_without_reloading_diffs():
|
||||
html = await dashboard()
|
||||
|
||||
@@ -418,7 +418,7 @@ async def test_starting_saved_today_work_closes_a_concurrent_rollover_planner():
|
||||
def test_plan_today_controller_is_available_in_the_offline_shell():
|
||||
source = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/plan-today.js'" in source
|
||||
assert "BASE + 'static/plan-today-readiness.js'" in source
|
||||
assert "BASE + 'static/plan-today-preview.js'" in source
|
||||
+1700
-23
File diff suppressed because it is too large.
Load diff
@@ -488,6 +488,59 @@ async def test_managed_session_statuses_apply_configured_idle_deadline_in_one_ca
|
||||
assert calls == [(["device-b", "device-a", "device-b"], 321)]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_managed_session_statuses_bind_batch_to_expected_principal(monkeypatch):
|
||||
calls = []
|
||||
|
||||
class Store:
|
||||
def managed_statuses(
|
||||
self, management_ids, *, idle_timeout_seconds, expected_principal_id
|
||||
):
|
||||
calls.append(
|
||||
(list(management_ids), idle_timeout_seconds, expected_principal_id)
|
||||
)
|
||||
return {management_id: "active" for management_id in set(management_ids)}
|
||||
|
||||
monkeypatch.setenv("STACKCHAIN_DASHBOARD_IDLE_TIMEOUT_SECONDS", "321")
|
||||
monkeypatch.setattr(dashboard_auth, "_session_store", lambda: Store())
|
||||
|
||||
assert await dashboard_auth.managed_session_statuses(
|
||||
["device-b", "device-a"], expected_principal_id=42
|
||||
) == {"device-a": "active", "device-b": "active"}
|
||||
assert calls == [(["device-b", "device-a"], 321, 42)]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_push_session_statuses_use_current_upstream_identity(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def current_user():
|
||||
return {"id": 42, "login": "timmy"}
|
||||
|
||||
async def statuses(management_ids, *, expected_principal_id):
|
||||
calls.append((list(management_ids), expected_principal_id))
|
||||
return {management_id: "active" for management_id in management_ids}
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "current_user", current_user)
|
||||
monkeypatch.setattr(main.dashboard_auth, "managed_session_statuses", statuses)
|
||||
|
||||
assert await main._identity_bound_push_session_statuses(["phone-device"]) == {
|
||||
"phone-device": "active"
|
||||
}
|
||||
assert calls == [(["phone-device"], 42)]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_push_session_statuses_fail_closed_when_identity_is_invalid(monkeypatch):
|
||||
async def current_user():
|
||||
return {"id": "not-an-integer", "login": "timmy"}
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "current_user", current_user)
|
||||
|
||||
with pytest.raises(ValueError, match="identity"):
|
||||
await main._identity_bound_push_session_statuses(["phone-device"])
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_push_poll_authorizes_delivery_against_managed_session(monkeypatch):
|
||||
captured = {}
|
||||
@@ -516,7 +569,7 @@ async def test_push_poll_authorizes_delivery_against_managed_session(monkeypatch
|
||||
await main._push_poll_loop()
|
||||
|
||||
assert captured["unread"] is main.gitea_proxy.unread_notification_snapshot
|
||||
assert captured["session_statuses"] is dashboard_auth.managed_session_statuses
|
||||
assert captured["session_statuses"] is main._identity_bound_push_session_statuses
|
||||
assert captured["max_concurrency"] == 3
|
||||
assert captured["max_individual_notifications"] == 4
|
||||
|
||||
|
||||
@@ -36,6 +36,40 @@ restored && first.refresh().then(status=>{
|
||||
assert output["keys"] == ["stackchain.release-receipt.v1:timmy"]
|
||||
|
||||
|
||||
def test_release_receipt_deletes_the_exact_captured_source_branch_without_stopping_release_tracking():
|
||||
output = run_node(r"""
|
||||
const values=new Map(), calls=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const receipt=createReleaseReceipt({storage,getLogin:()=> 'timmy',confirmAction:()=>true,fetchJson:async(path,options={})=>{
|
||||
calls.push({path,method:options.method||'GET',body:options.body||null});
|
||||
if ((options.method||'GET') === 'DELETE') return {number:7,deleted:true,source_branch:'timmy/feature',source_head_sha:'abc1234'};
|
||||
return {commit_sha:'merge456',ci_state:'pending',checks:[],release:null};
|
||||
}});
|
||||
const captured=receipt.capture(
|
||||
{repository:'stackchain/api',number:7,key:'stackchain/api#7'},
|
||||
{merge_commit_sha:'merge456',source_branch:'timmy/feature',source_head_sha:'abc1234',source_repository:'stackchain/api'}
|
||||
);
|
||||
(async()=>{
|
||||
await receipt.deleteBranch('stackchain/api','merge456');
|
||||
await receipt.refresh();
|
||||
process.stdout.write(JSON.stringify({captured,calls,restored:receipt.restore()}));
|
||||
})();
|
||||
""")
|
||||
|
||||
assert output["captured"]["source_branch"] == "timmy/feature"
|
||||
assert output["calls"][0] == {
|
||||
"path": "api/v1/repos/stackchain/api/pulls/7/source-branch",
|
||||
"method": "DELETE",
|
||||
"body": json.dumps({
|
||||
"source_branch": "timmy/feature",
|
||||
"expected_head_sha": "abc1234",
|
||||
}, separators=(",", ":")),
|
||||
}
|
||||
restored = output["restored"][0]
|
||||
assert restored["cleanup"] == {"state": "deleted", "message": "Source branch deleted."}
|
||||
assert restored["status"]["label"] == "Checks running"
|
||||
|
||||
|
||||
def test_receipt_distinguishes_failed_checks_waiting_for_release_and_exact_release():
|
||||
output = run_node(r"""
|
||||
const values=new Map();
|
||||
@@ -62,6 +96,132 @@ receipt.capture({repository:'stackchain/api',number:7,key:'stackchain/api#7'}, {
|
||||
assert output["restored"] == []
|
||||
|
||||
|
||||
def test_failed_release_check_loads_exact_commit_diagnostics_and_retries_single_flight():
|
||||
output = run_node(r"""
|
||||
const values=new Map(), calls=[];
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
let finishRetry;
|
||||
const receipt=createReleaseReceipt({storage,getLogin:()=> 'timmy',confirmAction:()=>true,fetchJson:async(path,options={})=>{
|
||||
calls.push({path,method:options.method||'GET'});
|
||||
if (path.endsWith('/failure')) return {commit_sha:'abc1234',run_id:91,job_index:3,name:'CI / browser',excerpt:'AssertionError: failed'};
|
||||
if (path.endsWith('/retry')) return await new Promise(resolve=>{finishRetry=()=>resolve({commit_sha:'abc1234',status:'queued'});});
|
||||
return {commit_sha:'abc1234',ci_state:'failure',checks:[{name:'CI / browser',state:'failure',description:'Playwright failed',url:'https://forge.example/git/stackchain/api/actions/runs/91/jobs/3',recovery:{run_id:91,job_index:3}}],release:null};
|
||||
}});
|
||||
receipt.capture({repository:'stackchain/api',number:7,key:'stackchain/api#7'}, {merge_commit_sha:'abc1234'});
|
||||
(async()=>{
|
||||
const failed=(await receipt.refresh())[0];
|
||||
const detail=await receipt.reviewFailure('stackchain/api','abc1234',91,3);
|
||||
const first=receipt.retryFailure('stackchain/api','abc1234',91,3);
|
||||
const second=receipt.retryFailure('stackchain/api','abc1234',91,3);
|
||||
await new Promise(resolve=>setTimeout(resolve,0)); finishRetry();
|
||||
const results=await Promise.all([first,second]);
|
||||
process.stdout.write(JSON.stringify({failed,detail,results,calls,after:receipt.restore()[0].status}));
|
||||
})();
|
||||
""")
|
||||
|
||||
assert output["failed"]["failures"] == [{
|
||||
"name": "CI / browser",
|
||||
"description": "Playwright failed",
|
||||
"url": "https://forge.example/git/stackchain/api/actions/runs/91/jobs/3",
|
||||
"recovery": {"run_id": 91, "job_index": 3},
|
||||
}]
|
||||
assert output["detail"]["commit_sha"] == "abc1234"
|
||||
assert output["detail"]["excerpt"] == "AssertionError: failed"
|
||||
assert output["results"] == [True, True]
|
||||
assert [call["method"] for call in output["calls"]] == ["GET", "GET", "POST"]
|
||||
assert output["calls"][1]["path"].endswith(
|
||||
"/pulls/7/release-receipt/abc1234/checks/91/jobs/3/failure"
|
||||
)
|
||||
assert output["calls"][2]["path"].endswith("/checks/91/jobs/3/retry")
|
||||
assert output["after"]["label"] == "Checks running"
|
||||
assert output["after"]["checks"] == []
|
||||
|
||||
|
||||
def test_failed_release_row_renders_phone_recovery_with_exact_sha_log_and_job_fallback():
|
||||
output = run_node(r"""
|
||||
function node(tag='div') { return {tag,children:[],hidden:false,textContent:'',className:'',disabled:false,append(...xs){this.children.push(...xs)},replaceChildren(...xs){this.children=[...xs]},setAttribute(k,v){this[k]=v},addEventListener(k,fn){this[k]=fn}}; }
|
||||
global.document={createElement:tag=>node(tag)};
|
||||
const values=new Map(), listNode=node();
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const receipt=createReleaseReceipt({storage,getLogin:()=> 'timmy',listNode,confirmAction:()=>true,fetchJson:async path=>{
|
||||
if (path.endsWith('/failure')) return {commit_sha:'abc1234',run_id:91,job_index:3,name:'CI / browser',excerpt:'AssertionError: mobile viewport overflow'};
|
||||
return {commit_sha:'abc1234',ci_state:'failure',checks:[{name:'CI / browser',state:'failure',description:'Playwright failed',url:'https://forge.example/git/stackchain/api/actions/runs/91/jobs/3',recovery:{run_id:91,job_index:3}}]};
|
||||
}});
|
||||
const flatten=root=>[root,...root.children.flatMap(flatten)];
|
||||
receipt.capture({repository:'stackchain/api',number:7,key:'stackchain/api#7'}, {merge_commit_sha:'abc1234'});
|
||||
(async()=>{
|
||||
await receipt.refresh();
|
||||
const review=flatten(listNode).find(value=>value.textContent==='Review failure');
|
||||
await review.click();
|
||||
const nodes=flatten(listNode);
|
||||
process.stdout.write(JSON.stringify({
|
||||
reviewLabel:review['aria-label'],
|
||||
texts:nodes.map(value=>value.textContent).filter(Boolean),
|
||||
links:nodes.filter(value=>value.tag==='a').map(value=>({text:value.textContent,href:value.href})),
|
||||
classes:nodes.map(value=>value.className).filter(Boolean),
|
||||
}));
|
||||
})();
|
||||
""")
|
||||
|
||||
assert output["reviewLabel"] == "Review failed check CI / browser for abc1234"
|
||||
assert "Merge abc1234" in output["texts"]
|
||||
assert "AssertionError: mobile viewport overflow" in output["texts"]
|
||||
assert "Retry failed check" in output["texts"]
|
||||
assert output["links"] == [{
|
||||
"text": "Open job",
|
||||
"href": "https://forge.example/git/stackchain/api/actions/runs/91/jobs/3",
|
||||
}]
|
||||
assert "release-failure-recovery" in output["classes"]
|
||||
|
||||
|
||||
def test_diagnosed_failed_release_prepares_one_rollback_pull_and_opens_mobile_workspace():
|
||||
output = run_node(r"""
|
||||
function node(tag='div') { return {tag,children:[],hidden:false,textContent:'',className:'',disabled:false,append(...xs){this.children.push(...xs)},replaceChildren(...xs){this.children=[...xs]},setAttribute(k,v){this[k]=v},addEventListener(k,fn){this[k]=fn}}; }
|
||||
global.document={createElement:tag=>node(tag)};
|
||||
const values=new Map(), calls=[], opened=[], listNode=node(), dialog={open:true,close(){this.open=false}};
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const receipt=createReleaseReceipt({
|
||||
storage,getLogin:()=> 'timmy',listNode,dialog,confirmAction:()=>true,openPull:pull=>opened.push(pull),
|
||||
fetchJson:async(path,options={})=>{
|
||||
calls.push({path,method:options.method||'GET'});
|
||||
if (path.endsWith('/failure')) return {commit_sha:'abc1234',run_id:91,job_index:3,name:'CI / browser',excerpt:'AssertionError: failed'};
|
||||
if (path.endsWith('/rollback')) return {repository:'stackchain/api',number:9,draft:true,url:'https://forge.example/git/stackchain/api/pulls/9',rollback_of:'abc1234'};
|
||||
return {commit_sha:'abc1234',ci_state:'failure',checks:[{name:'CI / browser',state:'failure',recovery:{run_id:91,job_index:3}}],release:null};
|
||||
},
|
||||
});
|
||||
const flatten=root=>[root,...root.children.flatMap(flatten)];
|
||||
receipt.capture({repository:'stackchain/api',number:7,key:'stackchain/api#7'}, {merge_commit_sha:'abc1234'});
|
||||
(async()=>{
|
||||
await receipt.refresh();
|
||||
const before=flatten(listNode).filter(value=>value.textContent==='Prepare rollback PR').length;
|
||||
await flatten(listNode).find(value=>value.textContent==='Review failure').click();
|
||||
const rollback=flatten(listNode).find(value=>value.textContent==='Prepare rollback PR');
|
||||
if (rollback) await rollback.click();
|
||||
process.stdout.write(JSON.stringify({before,found:!!rollback,calls,opened,dialogOpen:dialog.open,status:receipt.restore()[0].rollback||null}));
|
||||
})();
|
||||
""")
|
||||
|
||||
assert output["before"] == 0
|
||||
assert output["found"] is True
|
||||
assert output["calls"][-1] == {
|
||||
"path": "api/v1/repos/stackchain/api/pulls/7/release-receipt/abc1234/rollback",
|
||||
"method": "POST",
|
||||
}
|
||||
assert output["opened"] == [{
|
||||
"repository": "stackchain/api",
|
||||
"number": 9,
|
||||
"draft": True,
|
||||
"url": "https://forge.example/git/stackchain/api/pulls/9",
|
||||
"rollback_of": "abc1234",
|
||||
"kind": "pull",
|
||||
"key": "stackchain/api#9",
|
||||
"state": "open",
|
||||
}]
|
||||
assert output["dialogOpen"] is False
|
||||
assert output["status"]["state"] == "prepared"
|
||||
assert output["status"]["number"] == 9
|
||||
|
||||
|
||||
def test_watchlist_preserves_distinct_merges_deduplicates_and_dismisses_one():
|
||||
output = run_node(r"""
|
||||
const values=new Map();
|
||||
@@ -142,6 +302,25 @@ receipt.capture({repository:'stackchain/web',number:2,key:'stackchain/web#2'}, {
|
||||
assert [item["commit_sha"] for item in output["after"]] == ["pending"]
|
||||
|
||||
|
||||
def test_watchlist_renders_confirmed_touch_cleanup_for_the_exact_source_branch():
|
||||
output = run_node(r"""
|
||||
function node(tag='div') { return {tag,children:[],hidden:false,textContent:'',disabled:false,append(...xs){this.children.push(...xs)},replaceChildren(...xs){this.children=[...xs]},setAttribute(k,v){this[k]=v},addEventListener(k,fn){this[k]=fn}}; }
|
||||
global.document={createElement:tag=>node(tag)};
|
||||
const values=new Map(), calls=[], listNode=node();
|
||||
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
|
||||
const receipt=createReleaseReceipt({storage,getLogin:()=> 'timmy',listNode,confirmAction:()=>true,fetchJson:async(path,options={})=>{calls.push({path,method:options.method});return {deleted:true};}});
|
||||
receipt.capture({repository:'stackchain/api',number:7,key:'stackchain/api#7'}, {merge_commit_sha:'merge456',source_branch:'timmy/feature',source_head_sha:'abc1234',source_repository:'stackchain/api'});
|
||||
const row=listNode.children[0], copy=row.children[0], actions=row.children[1], cleanup=actions.children[0];
|
||||
(async()=>{ await cleanup.click(); process.stdout.write(JSON.stringify({branch:copy.children[2].textContent,cleanupText:cleanup.textContent,minLabel:cleanup['aria-label'],calls,after:receipt.restore()[0].cleanup})); })();
|
||||
""")
|
||||
|
||||
assert output["branch"] == "Branch timmy/feature · abc1234"
|
||||
assert output["cleanupText"] == "Delete source branch"
|
||||
assert output["minLabel"] == "Delete merged source branch timmy/feature at abc1234"
|
||||
assert output["calls"][0]["method"] == "DELETE"
|
||||
assert output["after"]["state"] == "deleted"
|
||||
|
||||
|
||||
def test_watchlist_polls_pending_merges_only_while_foregrounded():
|
||||
output = run_node(r"""
|
||||
const values=new Map(), scheduled=[], calls=[];
|
||||
@@ -214,8 +393,19 @@ def test_mobile_release_receipt_is_wired_into_the_merge_flow_and_phone_safe():
|
||||
assert 'id="release-receipt-launcher"' in html
|
||||
assert 'id="release-receipt-sheet"' in html
|
||||
assert 'id="release-watchlist"' in html
|
||||
assert 'releaseReceipt.capture(merging, mergeResult)' in dashboard
|
||||
assert 'rR.capture(merging, mergeResult)' in dashboard
|
||||
assert "listNode:qs('#release-watchlist')" in dashboard
|
||||
assert "openPull:openPullSheet" in dashboard
|
||||
assert "min-height:44px" in css[css.index(".release-receipt-sheet"):]
|
||||
assert "overflow-x:hidden" in css[css.index(".release-receipt-sheet"):]
|
||||
assert ".release-watchlist-item" in css
|
||||
assert ".release-watchlist-actions" in css
|
||||
cleanup_css = css[css.index(".release-watchlist-actions"):]
|
||||
assert "min-height:44px" in cleanup_css
|
||||
assert "grid-template-columns:1fr" in cleanup_css
|
||||
recovery_css = css[css.index(".release-failure-summary"):]
|
||||
assert "overflow-x:hidden" in recovery_css
|
||||
assert "white-space:pre-wrap" in recovery_css
|
||||
assert "min-height:44px" in recovery_css
|
||||
assert ".release-failure-actions" in recovery_css
|
||||
assert "grid-template-columns:1fr" in recovery_css
|
||||
@@ -123,6 +123,44 @@ def test_request_limits_are_route_specific_and_cover_api_mutations():
|
||||
assert main.request_body_limit("POST", "/unrelated") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_oversized_source_branch_delete_is_rejected_before_endpoint_work():
|
||||
downstream_called = False
|
||||
sent = []
|
||||
|
||||
async def downstream(_scope, _receive, _send):
|
||||
nonlocal downstream_called
|
||||
downstream_called = True
|
||||
|
||||
messages = iter(
|
||||
[
|
||||
{"type": "http.request", "body": b"x" * 40_000, "more_body": True},
|
||||
{"type": "http.request", "body": b"y" * 40_000, "more_body": False},
|
||||
]
|
||||
)
|
||||
|
||||
async def receive():
|
||||
return next(messages)
|
||||
|
||||
async def send(message):
|
||||
sent.append(message)
|
||||
|
||||
middleware = RequestBodyLimitMiddleware(downstream)
|
||||
await middleware(
|
||||
{
|
||||
"type": "http",
|
||||
"method": "DELETE",
|
||||
"path": "/api/v1/repos/stackchain/api/pulls/7/source-branch",
|
||||
"headers": [],
|
||||
},
|
||||
receive,
|
||||
send,
|
||||
)
|
||||
|
||||
assert sent[0]["status"] == 413
|
||||
assert downstream_called is False
|
||||
|
||||
|
||||
def test_pull_screenshot_upload_uses_binary_attachment_boundary():
|
||||
assert (
|
||||
main.request_body_limit(
|
||||
|
||||
@@ -108,6 +108,7 @@ async def test_gitea_review_detail_returns_bounded_actionable_checks(monkeypatch
|
||||
"name": "lint/<unsafe>", "state": "failure",
|
||||
"description": "Formatting failed " + "x" * 222,
|
||||
"url": "https://forge.example/git/stackchain/api/actions/runs/9/jobs/4",
|
||||
"recovery": {"run_id": 9, "job_index": 4},
|
||||
},
|
||||
{"name": "external", "state": "pending", "description": "Waiting", "url": ""},
|
||||
{"name": "build-release", "state": "success", "description": "Passed", "url": ""},
|
||||
|
||||
@@ -18,6 +18,11 @@ def security_access(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("STACKCHAIN_SESSION_DB", str(tmp_path / "sessions.sqlite3"))
|
||||
monkeypatch.setenv("STACKCHAIN_LOGIN_ATTEMPT_DB", str(tmp_path / "attempts.sqlite3"))
|
||||
monkeypatch.setenv("STACKCHAIN_SECURITY_EVENT_DB", str(tmp_path / "security.sqlite3"))
|
||||
|
||||
async def upstream_user():
|
||||
return {"id": 42, "login": "timmy"}
|
||||
|
||||
monkeypatch.setattr(main, "current_user", upstream_user)
|
||||
return tmp_path
|
||||
|
||||
|
||||
|
||||
@@ -6,6 +6,18 @@ from pathlib import Path
|
||||
SECURITY_CENTER = Path(__file__).parents[1] / "frontend" / "security-center.js"
|
||||
|
||||
|
||||
def test_source_branch_cleanup_has_a_specific_security_activity_label():
|
||||
source = SECURITY_CENTER.read_text()
|
||||
|
||||
assert "source_branch_deleted: 'Source branch deleted'" in source
|
||||
|
||||
|
||||
def test_release_rollback_has_a_specific_security_activity_label():
|
||||
source = SECURITY_CENTER.read_text()
|
||||
|
||||
assert "release_rollback_prepared: 'Release rollback prepared'" in source
|
||||
|
||||
|
||||
def test_open_security_center_loads_all_sections_concurrently_and_is_awaitable():
|
||||
harness = f"""
|
||||
const attachSecurityCenter=require({json.dumps(str(SECURITY_CENTER))});
|
||||
|
||||
@@ -189,7 +189,7 @@ async function dispatchPush(payload) {{
|
||||
def test_week_unplan_undo_rolls_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/week-plan.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
|
||||
@@ -197,20 +197,20 @@ def test_week_unplan_undo_rolls_the_offline_shell():
|
||||
def test_private_today_action_mailbox_rolls_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
|
||||
|
||||
def test_per_day_week_conflict_ui_rolls_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/week-plan.js'" in source
|
||||
|
||||
|
||||
def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/my-work.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
@@ -219,7 +219,7 @@ def test_resumable_today_session_ships_in_a_new_offline_shell():
|
||||
def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/authored-outbox.js'" in source
|
||||
assert "BASE + 'static/background-issue-sync.js'" in source
|
||||
@@ -228,7 +228,7 @@ def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
|
||||
def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/issue-evidence-review.js'" in source
|
||||
assert "BASE + 'static/issue-attachment.js'" in source
|
||||
|
||||
@@ -236,14 +236,14 @@ def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
|
||||
def test_ownership_exit_runtime_rolls_the_offline_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
|
||||
def test_offline_review_next_ships_today_completion_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/today-completion.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -251,7 +251,7 @@ def test_offline_review_next_ships_today_completion_atomically():
|
||||
def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/create-issue-sheet.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
|
||||
@@ -259,7 +259,7 @@ def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
|
||||
def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/issue-sheet.js'" in source
|
||||
assert "BASE + 'static/checklist-conflict.js'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
@@ -269,14 +269,14 @@ def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
|
||||
def test_exact_later_picker_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/later-picker.js'" in source
|
||||
|
||||
|
||||
def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/dashboard.css'" in source
|
||||
assert "BASE + 'static/dashboard.js'" in source
|
||||
assert "BASE + 'static/install-app.js'" in source
|
||||
@@ -285,21 +285,21 @@ def test_navigation_deadline_ships_in_a_new_shell_cache():
|
||||
def test_today_convergence_ships_in_a_new_shell_cache():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
def test_mobile_search_viewport_ships_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/mobile-search-viewport.js'" in source
|
||||
|
||||
|
||||
def test_update_ownership_flow_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/update-ownership.js'" in source
|
||||
|
||||
|
||||
@@ -1354,7 +1354,7 @@ def test_one_session_bound_csrf_proof_is_reused_for_a_background_drain():
|
||||
def test_queue_today_ships_atomically_in_a_new_offline_shell():
|
||||
source = WORKER.read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/queue-today.js'" in source
|
||||
|
||||
|
||||
@@ -1467,6 +1467,7 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
|
||||
"/dashboard/static/voice-issue-capture.js",
|
||||
"/dashboard/static/voice-conversation-capture.js",
|
||||
"/dashboard/static/create-issue-sheet.js",
|
||||
"/dashboard/static/create-pull-sheet.js",
|
||||
"/dashboard/static/mobile-create-issue-nav.js",
|
||||
"/dashboard/static/create-and-start.js",
|
||||
"/dashboard/static/assign-and-start.js",
|
||||
|
||||
@@ -88,6 +88,23 @@ def test_session_status_reports_idle_without_background_validation_extending_act
|
||||
assert store.status("phone-session", 3_000, idle_timeout_seconds=900) == "idle"
|
||||
|
||||
|
||||
def test_active_session_status_carries_bound_upstream_identity(tmp_path):
|
||||
store = SessionStore(tmp_path / "sessions.sqlite3", clock=lambda: 1_000.0)
|
||||
|
||||
store.activate(
|
||||
"phone-session",
|
||||
3_000,
|
||||
principal_id=42,
|
||||
principal_login="timmy",
|
||||
)
|
||||
|
||||
status = store.status("phone-session", 3_000, idle_timeout_seconds=900)
|
||||
|
||||
assert status == "active"
|
||||
assert status.principal_id == 42
|
||||
assert status.principal_login == "timmy"
|
||||
|
||||
|
||||
def test_managed_session_status_enforces_absolute_and_idle_expiry(tmp_path):
|
||||
now = [1_000.0]
|
||||
store = SessionStore(tmp_path / "sessions.sqlite3", clock=lambda: now[0])
|
||||
@@ -134,6 +151,49 @@ def test_managed_session_statuses_classify_a_batch_with_one_read(tmp_path, monke
|
||||
]
|
||||
|
||||
|
||||
def test_managed_session_statuses_reject_other_and_legacy_principals_in_one_read(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
store = SessionStore(tmp_path / "sessions.sqlite3", clock=lambda: 1_000.0)
|
||||
store.activate(
|
||||
"matching-session",
|
||||
3_000,
|
||||
management_id="matching-device",
|
||||
principal_id=42,
|
||||
principal_login="timmy",
|
||||
)
|
||||
store.activate(
|
||||
"other-session",
|
||||
3_000,
|
||||
management_id="other-device",
|
||||
principal_id=84,
|
||||
principal_login="other",
|
||||
)
|
||||
store.activate("legacy-session", 3_000, management_id="legacy-device")
|
||||
statements = []
|
||||
connect = sqlite3.connect
|
||||
|
||||
def traced_connect(*args, **kwargs):
|
||||
connection = connect(*args, **kwargs)
|
||||
connection.set_trace_callback(statements.append)
|
||||
return connection
|
||||
|
||||
monkeypatch.setattr(session_store.sqlite3, "connect", traced_connect)
|
||||
|
||||
assert store.managed_statuses(
|
||||
["matching-device", "other-device", "legacy-device"],
|
||||
idle_timeout_seconds=900,
|
||||
expected_principal_id=42,
|
||||
) == {
|
||||
"matching-device": "active",
|
||||
"other-device": "principal_mismatch",
|
||||
"legacy-device": "principal_mismatch",
|
||||
}
|
||||
assert [statement for statement in statements if statement.lstrip().upper().startswith("SELECT")] == [
|
||||
next(statement for statement in statements if "FROM active_sessions" in statement)
|
||||
]
|
||||
|
||||
|
||||
def test_managed_session_statuses_skips_database_for_an_empty_batch(tmp_path, monkeypatch):
|
||||
store = SessionStore(tmp_path / "sessions.sqlite3", clock=lambda: 1_000.0)
|
||||
monkeypatch.setattr(store, "_connect", lambda *args, **kwargs: pytest.fail("database opened"))
|
||||
@@ -230,6 +290,30 @@ def test_idle_status_migrates_existing_registry_and_starts_legacy_idle_clock_now
|
||||
assert last_active_at == 1_000
|
||||
|
||||
|
||||
def test_identity_status_migrates_registry_that_already_has_idle_tracking(tmp_path):
|
||||
database = tmp_path / "sessions.sqlite3"
|
||||
digest = SessionStore._digest("existing-session")
|
||||
with sqlite3.connect(database) as connection:
|
||||
connection.execute(
|
||||
"CREATE TABLE active_sessions ("
|
||||
"session_hash TEXT PRIMARY KEY, expires_at INTEGER NOT NULL, "
|
||||
"management_id TEXT, device_label TEXT, created_at INTEGER, last_active_at INTEGER"
|
||||
")"
|
||||
)
|
||||
connection.execute(
|
||||
"INSERT INTO active_sessions VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(digest, 2_000, "legacy-device", "Existing device", 900, 1_000),
|
||||
)
|
||||
|
||||
status = SessionStore(database, clock=lambda: 1_000.0).status(
|
||||
"existing-session", 2_000, idle_timeout_seconds=900
|
||||
)
|
||||
|
||||
assert status == "active"
|
||||
assert status.principal_id is None
|
||||
assert status.principal_login is None
|
||||
|
||||
|
||||
def test_existing_session_can_mint_first_step_up_grant_during_schema_upgrade(tmp_path):
|
||||
database = tmp_path / "sessions.sqlite3"
|
||||
digest = SessionStore._digest("existing-session")
|
||||
|
||||
@@ -221,7 +221,7 @@ async def test_today_blocker_opens_existing_preview_and_preserves_readiness_gate
|
||||
def test_readiness_runtime_is_available_in_offline_shell():
|
||||
service_worker = SERVICE_WORKER.read_text()
|
||||
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v138';" in service_worker
|
||||
assert "const CACHE = 'stackchain-dashboard-shell-v139';" in service_worker
|
||||
assert "BASE + 'static/today-readiness.js'" in service_worker
|
||||
|
||||
|
||||
|
||||
@@ -248,9 +248,9 @@ def test_dashboard_connects_recap_and_wrap_up_to_a_mobile_summary_review_sheet()
|
||||
assert ".today-summary-actions button { min-height:44px;" in css
|
||||
assert ".today-summary-panel" in css and "overflow-x:hidden" in css
|
||||
assert ".today-summary-destination" in css and "overflow-wrap:anywhere" in css
|
||||
assert "tests/e2e/test_mobile_today_summary_release.py" in (
|
||||
ROOT / ".gitea" / "workflows" / "ci.yml"
|
||||
).read_text()
|
||||
workflow = (ROOT / ".gitea" / "workflows" / "ci.yml").read_text()
|
||||
assert "python3 -m pytest tests/e2e -q" in workflow
|
||||
assert (ROOT / "tests/e2e/test_mobile_today_summary_release.py").is_file()
|
||||
|
||||
|
||||
def test_summary_uses_the_human_label_from_recap_feedback_rows():
|
||||
|
||||
@@ -343,7 +343,7 @@ listeners['stackchain:first-task-complete']();
|
||||
def test_inflight_today_drain_ships_in_a_new_offline_shell():
|
||||
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
|
||||
|
||||
assert "stackchain-dashboard-shell-v138" in source
|
||||
assert "stackchain-dashboard-shell-v139" in source
|
||||
assert "BASE + 'static/today-sync.js'" in source
|
||||
|
||||
|
||||
|
||||
@@ -157,7 +157,9 @@ def test_dashboard_packages_a_mobile_wrap_up_dialog_and_opens_it_after_recap_sav
|
||||
assert 'openWrapUp(handoff.actual_minutes, workedItems)' in recap
|
||||
assert '.today-wrap-up-actions button { min-height:44px;' in css
|
||||
assert '.today-wrap-up-panel' in css and 'overflow-x:hidden' in css
|
||||
assert 'tests/e2e/test_mobile_today_wrap_up_release.py' in (ROOT / '.gitea' / 'workflows' / 'ci.yml').read_text()
|
||||
workflow = (ROOT / '.gitea' / 'workflows' / 'ci.yml').read_text()
|
||||
assert 'python3 -m pytest tests/e2e -q' in workflow
|
||||
assert (ROOT / 'tests/e2e/test_mobile_today_wrap_up_release.py').is_file()
|
||||
|
||||
|
||||
def test_wrap_up_repeat_confirmation_does_not_repeat_tomorrow_or_today_operations():
|
||||
|
||||
@@ -90,6 +90,47 @@ async def test_filed_work_page_endpoint_preserves_authored_reason(monkeypatch):
|
||||
assert response.json()["items"][0]["work_reasons"] == ["created_by_me"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_authored_pull_page_endpoint_preserves_authorship_reason(monkeypatch):
|
||||
async def page_loader(stream, page):
|
||||
assert (stream, page) == ("authored", 2)
|
||||
return {
|
||||
"stream": stream, "page": page, "total": 51, "has_more": False,
|
||||
"items": [{
|
||||
"id": 901, "number": 41, "title": "Ship mobile flow", "state": "open",
|
||||
"user": {"login": "timmy"}, "labels": [], "assignees": [],
|
||||
"work_reasons": ["authored_by_me"],
|
||||
"repository": {"full_name": "stackchain/dashboard"},
|
||||
"html_url": "https://forge.example/pulls/41",
|
||||
}],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(main.gitea_proxy, "work_page", page_loader)
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
response = await client.get("/api/v1/work/authored?page=2")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["items"][0]["work_reasons"] == ["authored_by_me"]
|
||||
|
||||
|
||||
def test_initial_context_preserves_authored_pull_reason():
|
||||
payload = main._context_payload(
|
||||
{"id": 1, "login": "timmy"},
|
||||
[],
|
||||
[],
|
||||
[{
|
||||
"id": 901, "number": 41, "title": "Ship mobile flow", "state": "open",
|
||||
"user": {"login": "timmy"}, "labels": [], "assignees": [],
|
||||
"work_reasons": ["authored_by_me"],
|
||||
"repository": {"full_name": "stackchain/dashboard"},
|
||||
"html_url": "https://forge.example/pulls/41",
|
||||
}],
|
||||
)
|
||||
|
||||
assert payload["pull_requests"][0]["work_reasons"] == ["authored_by_me"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_pwa_assets_expose_root_scoped_share_target_without_caching_api_data():
|
||||
transport = httpx.ASGITransport(app=main.app)
|
||||
|
||||
@@ -107,6 +107,36 @@ async def test_resolve_work_route_returns_only_a_requested_review():
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_work_route_returns_an_open_authored_unassigned_pull():
|
||||
async def upstream(request):
|
||||
if request.url.path.endswith("/user"):
|
||||
return httpx.Response(200, json={"login": "timmy"})
|
||||
return httpx.Response(200, json={
|
||||
"id": 703,
|
||||
"number": 90,
|
||||
"title": "Ship authored flow",
|
||||
"state": "open",
|
||||
"html_url": gitea_proxy.GITEA_URL + "/stackchain/dashboard/pulls/90",
|
||||
"assignees": [],
|
||||
"requested_reviewers": [],
|
||||
"user": {"login": "timmy"},
|
||||
})
|
||||
|
||||
gitea_proxy.start_client(transport=httpx.MockTransport(upstream))
|
||||
try:
|
||||
result = await gitea_proxy.resolve_work_route(
|
||||
"pull", "stackchain/dashboard", 90, None
|
||||
)
|
||||
finally:
|
||||
await gitea_proxy.stop_client()
|
||||
|
||||
assert result["kind"] == "pull"
|
||||
assert result["number"] == 90
|
||||
assert result["is_assigned"] is False
|
||||
assert result["work_reasons"] == ["authored_by_me"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_resolve_work_route_returns_an_open_issue_filed_by_the_current_user():
|
||||
requests = []
|
||||
|
||||
Reference in new issue
Block a user