fix(edit): send blob sha in Contents API PUT (Gitea 28 UpdateFile contract)

Gitea 28 decides create-vs-update solely by the body 'sha' (blob ID): empty sha -> create (422 'already exists' on an existing file), stale sha -> 422 'does not match'. The client sent last_commit_sha, which Gitea 28 bodies ignore - every save was a CREATE, so nothing ever reached the branch. fetchDoc/putBase64 now carry the file's blob sha, save reads the new sha from FileResponse.content.sha, and save-conflict detection accepts 412 (older Gitea) or 422 with a 'does not match' message; other 422s stay a hard failure with resume. Spec 6.1 amended with dated note; AGENTS.md DraftStore line aligned.
This commit is contained in:
dong.nguyen committed 2026-10-23 09:51:28 +07:00
1 parent caa4242100
commit 2ac7a5dd13
3 files changed
+46 -25

No files matched your search

+1 -1
View File
@@ -87,7 +87,7 @@ Content is split once, at authoring time, into language-neutral **structure docu
- Entry: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code). The shell authenticates, fetches the live master documents through the proxy, and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview - Entry: any route with `?edit` — `MaybeEditMode` in `App.tsx` lazy-mounts `EditModeShell` (its own chunk; visitors never load edit code). The shell authenticates, fetches the live master documents through the proxy, and re-wraps the tree in an `I18nProvider` override — the seven routes ARE the preview
- Target branch (spec D10): `?edit=<branch>` reads (`?ref=`) and writes (`branch` in the PUT body) that branch; a bare `?edit` resumes the session's last branch, default `master`. Names are validated against git ref rules in `src/i18n/edit-mode.ts` before any request (illegal → exit like a failed auth); the branch is stored beside the session flag. The target branch must already exist — Contents API updates never create branches. Only `master` deploys, so the EditBar shows a merge hint on other branches - Target branch (spec D10): `?edit=<branch>` reads (`?ref=`) and writes (`branch` in the PUT body) that branch; a bare `?edit` resumes the session's last branch, default `master`. Names are validated against git ref rules in `src/i18n/edit-mode.ts` before any request (illegal → exit like a failed auth); the branch is stored beside the session flag. The target branch must already exist — Contents API updates never create branches. Only `master` deploys, so the EditBar shows a merge hint on other branches
- Auth: HTTP Basic at the nginx `/api/content/` proxy is the security boundary; `src/i18n/edit-mode.ts` probes it through a hidden iframe, keeps the session flag `portfolio-edit` in sessionStorage, and strips `?edit` when the probe fails (401 or cancelled prompt → normal visitor site) - Auth: HTTP Basic at the nginx `/api/content/` proxy is the security boundary; `src/i18n/edit-mode.ts` probes it through a hidden iframe, keeps the session flag `portfolio-edit` in sessionStorage, and strips `?edit` when the probe fails (401 or cancelled prompt → normal visitor site)
- `src/i18n/draft.ts` — `DraftStore`: baselines (`data` + `last_commit_sha`) of the six content documents, copy-on-write draft, leaf-path diff, cross-document validation on every accepted edit, three-way rebase on 412 conflicts (origin / base / working kept separate), draft persisted to sessionStorage `portfolio-draft`, sequential-PUT save (one commit per touched document, resume from the first unwritten one on failure), and appending new id union members to `src/types/index.ts` after their documents land - `src/i18n/draft.ts` — `DraftStore`: baselines (`data` + blob `sha`) of the six content documents, copy-on-write draft, leaf-path diff, cross-document validation on every accepted edit, three-way rebase on save conflicts (Gitea 28 reports a blob-sha mismatch as 422 with a "does not match" message; older deployments answered 412 — both are handled; origin / base / working kept separate), draft persisted to sessionStorage `portfolio-draft`, sequential-PUT save (one commit per touched document, resume from the first unwritten one on failure), and appending new id union members to `src/types/index.ts` after their documents land
- `src/components/ui/EditableText.tsx` — the site's own element (`as` = the tag or motion component it renders today) becomes the inline editor only in edit mode; commit on blur only (Vietnamese IME-safe), Esc cancels, Enter commits single-line fields, paste is plain-text, empty required values are rejected at commit; without an `EditContext` provider it renders byte-identical markup to the plain element - `src/components/ui/EditableText.tsx` — the site's own element (`as` = the tag or motion component it renders today) becomes the inline editor only in edit mode; commit on blur only (Vietnamese IME-safe), Esc cancels, Enter commits single-line fields, paste is plain-text, empty required values are rejected at commit; without an `EditContext` provider it renders byte-identical markup to the plain element
- `src/components/layout/EditBar.tsx` — fixed save bar: per-path diff with revert, conflict resolution (rebase / take-theirs / hand-merge), per-document save status, partial-save resume, exit confirm; `src/components/layout/JsonPanel.tsx` — per-document JSON editor with shape hints, record templates (structure + text stubs created together), orphan-free record delete, read-only `ui.json` tabs - `src/components/layout/EditBar.tsx` — fixed save bar: per-path diff with revert, conflict resolution (rebase / take-theirs / hand-merge), per-document save status, partial-save resume, exit confirm; `src/components/layout/JsonPanel.tsx` — per-document JSON editor with shape hints, record templates (structure + text stubs created together), orphan-free record delete, read-only `ui.json` tabs
- Editable surface is content text only (bio, tagline segments, project titles/summaries/section prose, experience titles/responsibilities, skill-group titles, philosophy titles/descriptions); structure fields (`featured`, `variant`, technologies, links, ids) are edited in the JSON panel; `ui.json` is read-only in v4. **Design agreed 2026-10-23 (`spec-v4-inline-editing.md`), not yet implemented:** the JSON panel will be deleted — pencil-icon-trigger inline editing with field-provenance chips (`document → pointer`), chip-level tag editors, ghost add/delete/move record controls, per-record settings popover, auto-generated ids, handle-only social links with loader-derived URLs - Editable surface is content text only (bio, tagline segments, project titles/summaries/section prose, experience titles/responsibilities, skill-group titles, philosophy titles/descriptions); structure fields (`featured`, `variant`, technologies, links, ids) are edited in the JSON panel; `ui.json` is read-only in v4. **Design agreed 2026-10-23 (`spec-v4-inline-editing.md`), not yet implemented:** the JSON panel will be deleted — pencil-icon-trigger inline editing with field-provenance chips (`document → pointer`), chip-level tag editors, ghost add/delete/move record controls, per-record settings popover, auto-generated ids, handle-only social links with loader-derived URLs
+6 -5
View File
@@ -285,7 +285,7 @@ graph LR
subgraph edit["Edit time (new)"] subgraph edit["Edit time (new)"]
V2["edit mode"] --> DR["draft state<br/>= the same JSON documents"] V2["edit mode"] --> DR["draft state<br/>= the same JSON documents"]
DR -->|"validate before save"| DR DR -->|"validate before save"| DR
DR -->|"PUT + last_commit_sha"| PX["nginx /api/content/<br/>basic auth + token"] DR -->|"PUT + blob sha"| PX["nginx /api/content/<br/>basic auth + token"]
PX --> GA["Gitea Contents API"] --> COMMIT["commit on master"] --> CI PX --> GA["Gitea Contents API"] --> COMMIT["commit on master"] --> CI
end end
``` ```
@@ -329,7 +329,7 @@ Type changes in `src/types/index.ts`: every `*En` optional is deleted from the 6
The site itself gains an edit mode. There is no second preview machinery — the seven routes *are* the preview. The site itself gains an edit mode. There is no second preview machinery — the seven routes *are* the preview.
- **Entry:** edit mode activates only for the authenticated owner (handshake against the protected proxy endpoint, §6.2; activation stored in `sessionStorage`; a `?edit` query on any route re-enters the mode within a session; the query is stripped from the URL on exit so shared/canonical URLs stay clean). Anonymous visitors never see edit affordances. - **Entry:** edit mode activates only for the authenticated owner (handshake against the protected proxy endpoint, §6.2; activation stored in `sessionStorage`; a `?edit` query on any route re-enters the mode within a session; the query is stripped from the URL on exit so shared/canonical URLs stay clean). Anonymous visitors never see edit affordances.
- **Draft initialization:** the draft is initialized from **live repository files fetched through the proxy** (`GET` per document + its `last_commit_sha`), not from the bundle — the bundle may be older than master if anyone edited via Gitea web since the last build, and a bundle-seeded draft would silently revert those edits. The static bundle is used only as an offline fallback, with a visible "stale" warning. - **Draft initialization:** the draft is initialized from **live repository files fetched through the proxy** (`GET` per document + its blob `sha`), not from the bundle — the bundle may be older than master if anyone edited via Gitea web since the last build, and a bundle-seeded draft would silently revert those edits. The static bundle is used only as an offline fallback, with a visible "stale" warning.
- **Mechanism:** edit mode wraps `<Layout>` in `<I18nProvider override={draft}>`. All pages, all components, both languages render the draft — text **and** structure. - **Mechanism:** edit mode wraps `<Layout>` in `<I18nProvider override={draft}>`. All pages, all components, both languages render the draft — text **and** structure.
- **Inline text editing:** rendered text nodes bound to a text-document path become editable on focus (`contentEditable`); blur writes `{ path, value }` into the draft. Editing `projects['iot-dws-integration'].title` updates the card on `/projects`, the header on `/projects/:id`, and the featured block on the home page **simultaneously** — one draft, every consumer. - **Inline text editing:** rendered text nodes bound to a text-document path become editable on focus (`contentEditable`); blur writes `{ path, value }` into the draft. Editing `projects['iot-dws-integration'].title` updates the card on `/projects`, the header on `/projects/:id`, and the featured block on the home page **simultaneously** — one draft, every consumer.
- **Editable surface (curated scope):** inline editing covers **text documents only** — profile bio and tagline (each tagline segment is an individually editable span), profile subtitle / career TL;DR / philosophy quote titles+paragraphs (row 18), project titles/summaries/section content/role, experience titles/companies/durations/responsibilities (row 19), skill group titles, philosophy titles/descriptions. `ui.json` is **read-only** in v4 (labels/aria are low-frequency chrome). This bounds the wrapping work to the ~40 content render sites, not the 130+ UI-string sites. Adjacent tagline segments are separate edit targets — the caret does not cross a segment boundary; intended behavior (D9), not a bug. *Superseded 2026-10-23 by `spec-v4-inline-editing.md`: editing is triggered by a per-field pencil icon, never by text focus; tag arrays (`currentInterests`, `roles`, `keywords`, `metrics`, `technologies`, tagline segments + emphasis toggle) become chip-level edit units with add/delete/move.* - **Editable surface (curated scope):** inline editing covers **text documents only** — profile bio and tagline (each tagline segment is an individually editable span), profile subtitle / career TL;DR / philosophy quote titles+paragraphs (row 18), project titles/summaries/section content/role, experience titles/companies/durations/responsibilities (row 19), skill group titles, philosophy titles/descriptions. `ui.json` is **read-only** in v4 (labels/aria are low-frequency chrome). This bounds the wrapping work to the ~40 content render sites, not the 130+ UI-string sites. Adjacent tagline segments are separate edit targets — the caret does not cross a segment boundary; intended behavior (D9), not a bug. *Superseded 2026-10-23 by `spec-v4-inline-editing.md`: editing is triggered by a per-field pencil icon, never by text focus; tag arrays (`currentInterests`, `roles`, `keywords`, `metrics`, `technologies`, tagline segments + emphasis toggle) become chip-level edit units with add/delete/move.*
@@ -356,7 +356,7 @@ stateDiagram-v2
``` ```
- **Entry:** `?edit` on any route → the app probes the protected endpoint once (hidden-iframe GET to trigger the native Basic prompt, §6.2). 401 or cancel → normal visitor site, zero affordances. Auth OK → session flag in `sessionStorage` + draft initialization (§5.1). Within a session the browser re-attaches Basic credentials to later requests on its own — no repeated prompt. The probe targets the session's branch: `?edit=<branch>` selects it, a bare `?edit` resumes the last one or `master` (D10); the branch name is validated before the probe and stored beside the session flag. - **Entry:** `?edit` on any route → the app probes the protected endpoint once (hidden-iframe GET to trigger the native Basic prompt, §6.2). 401 or cancel → normal visitor site, zero affordances. Auth OK → session flag in `sessionStorage` + draft initialization (§5.1). Within a session the browser re-attaches Basic credentials to later requests on its own — no repeated prompt. The probe targets the session's branch: `?edit=<branch>` selects it, a bare `?edit` resumes the last one or `master` (D10); the branch name is validated before the probe and stored beside the session flag.
- **Durability:** every accepted edit is also copied to `sessionStorage` (the documents are tens of KB). An accidental reload restores the draft: the app re-fetches live files, re-applies the saved draft, and flags any document whose `last_commit_sha` moved → conflict flow (§5.6). SPA navigation never loses the draft; `beforeunload` warns while dirty. - **Durability:** every accepted edit is also copied to `sessionStorage` (the documents are tens of KB). An accidental reload restores the draft: the app re-fetches live files, re-applies the saved draft, and flags any document whose blob `sha` moved → conflict flow (§5.6). SPA navigation never loses the draft; `beforeunload` warns while dirty.
- **Exit:** explicit action in the EditBar — save-or-discard prompt if dirty, clear flag + draft, `history.replaceState` strips `?edit`. - **Exit:** explicit action in the EditBar — save-or-discard prompt if dirty, clear flag + draft, `history.replaceState` strips `?edit`.
### 5.3 `EditableText` contract (inline editing) ### 5.3 `EditableText` contract (inline editing)
@@ -414,8 +414,8 @@ v4 exposes no new layout knobs. `featured` and `variant` already exist and are e
Repo: `https://code.vugado.com/dong.nguyen/cv` — self-hosted Gitea (API verified live: `/api/v1/version` → 28.1.0). Contents API paths are fixed to this repo: Repo: `https://code.vugado.com/dong.nguyen/cv` — self-hosted Gitea (API verified live: `/api/v1/version` → 28.1.0). Contents API paths are fixed to this repo:
- `GET /api/v1/repos/dong.nguyen/cv/contents/{path}` — read the live file + its `last_commit_sha` when a draft session starts (§5.1). - `GET /api/v1/repos/dong.nguyen/cv/contents/{path}` — read the live file + its blob `sha` when a draft session starts (§5.1).
- `PUT /api/v1/repos/dong.nguyen/cv/contents/{path}` — body: base64 content, `message`, `branch`, `last_commit_sha`. A stale sha → 412 → editor refetches and re-applies; lost updates are impossible. - `PUT /api/v1/repos/dong.nguyen/cv/contents/{path}` — body: base64 content, `message`, `branch`, `sha` (the file's blob ID). Gitea 28 `UpdateFile` keys create-vs-update on this field: empty `sha` → create (an existing file answers 422 "repository file already exists"); a stale `sha` → 422 with a "does not match" message → editor refetches and re-applies; lost updates are impossible. *(Amended 2026-10-23 after the first real save against 28.1.0 — the text previously described the retired `last_commit_sha`/412 contract; `last_commit_sha` exists only in responses.)*
**Save/CI policy (decided):** a save writes its touched documents as **sequential PUTs to `master`** — each is one commit and triggers the existing pipeline. Consequences accepted: a save touching 2–4 documents produces 2–4 sequential CI runs, and between runs the deployed site can transiently mix old/new documents. For a single owner publishing at low frequency this is the boring, correct choice; the final state after the last pipeline is always consistent. (Branch-then-merge for a single pipeline run is noted as a future optimization, not v4.) **Save/CI policy (decided):** a save writes its touched documents as **sequential PUTs to `master`** — each is one commit and triggers the existing pipeline. Consequences accepted: a save touching 2–4 documents produces 2–4 sequential CI runs, and between runs the deployed site can transiently mix old/new documents. For a single owner publishing at low frequency this is the boring, correct choice; the final state after the last pipeline is always consistent. (Branch-then-merge for a single pipeline run is noted as a future optimization, not v4.)
@@ -598,3 +598,4 @@ Deferred (not v4):
| 17 | Target-branch editing (D10): `?edit=<branch>`, `?ref=` on GET, `branch` on PUT, branch chip + merge hint | 3 | ✅ Done 2026-10-22 (automated) — tri-state URL parsing with git-ref validation (`edit-mode.ts`), `?ref=` on every document GET and `branch` in every PUT body (`draft.ts`, incl. the 412-refresh and id-union legs), branch persisted beside the session flag, EditBar branch chip + merge hint on non-default branches (`ui.json` `branchLabel`/`mergeHint`). Verified: `pnpm build`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 7/7, throwaway wiring smoke (URL tri-state, ref/branch transport, EditBar render for branch vs master) — deleted after the run. ⬜ Browser + Gitea: edit on a non-master branch → commits land there; merge → deploy | | 17 | Target-branch editing (D10): `?edit=<branch>`, `?ref=` on GET, `branch` on PUT, branch chip + merge hint | 3 | ✅ Done 2026-10-22 (automated) — tri-state URL parsing with git-ref validation (`edit-mode.ts`), `?ref=` on every document GET and `branch` in every PUT body (`draft.ts`, incl. the 412-refresh and id-union legs), branch persisted beside the session flag, EditBar branch chip + merge hint on non-default branches (`ui.json` `branchLabel`/`mergeHint`). Verified: `pnpm build`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 7/7, throwaway wiring smoke (URL tri-state, ref/branch transport, EditBar render for branch vs master) — deleted after the run. ⬜ Browser + Gitea: edit on a non-master branch → commits land there; merge → deploy |
| 18 | Move the three person-content keys out of `ui.json` (§11): `about.subtitle` → `profile.subtitle`, `experience.tldrText` → `profile.tldr`, `philosophy.quotes` → `profile.philosophyQuotes`; extend `ProfileText`, repoint 4 call sites, `EditableText` wrap + `SectionHeading` `subtitle: ReactNode`, JsonPanel hint update; `tsc` is the migration net | post-v4 | ✅ Done 2026-10-22 (automated) — values in both `content.{vi,en}.json`, keys deleted from both `ui` documents, `edit.fields` labels added; verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 7/7, throwaway SSR smoke asserting the subtitle / TL;DR / essay markers on `/about`, home + `/experience`, `/philosophy` in both languages — deleted after the run. ⬜ Browser: inline-edit the three fields in `?edit` | | 18 | Move the three person-content keys out of `ui.json` (§11): `about.subtitle` → `profile.subtitle`, `experience.tldrText` → `profile.tldr`, `philosophy.quotes` → `profile.philosophyQuotes`; extend `ProfileText`, repoint 4 call sites, `EditableText` wrap + `SectionHeading` `subtitle: ReactNode`, JsonPanel hint update; `tsc` is the migration net | post-v4 | ✅ Done 2026-10-22 (automated) — values in both `content.{vi,en}.json`, keys deleted from both `ui` documents, `edit.fields` labels added; verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 7/7, throwaway SSR smoke asserting the subtitle / TL;DR / essay markers on `/about`, home + `/experience`, `/philosophy` in both languages — deleted after the run. ⬜ Browser: inline-edit the three fields in `?edit` |
| 19 | Localize the §4 structure-assigned strings (`experience.company` of non-company entries, `duration`, `currentInterests`, `roles`, `keywords`, `projects.role`/`metrics`) or keep them EN-only like `technologies` | post-v4 | ✅ Done 2026-10-22 (automated) — fields moved to the text documents (§4 follow-up); VI document carries localized values (numeric dates + "nay", "Sẵn sàng cho cơ hội mới", "Nghỉ giữa chặng", "Đã triển khai tại 16 sortations", "Xử lý 70.000 ảnh/tháng"), en overrides with the originals, proper nouns and term lists identical (en omits); company/duration/role inline-editable, tag arrays JSON-panel-only; templates in `draft.ts` and JsonPanel hints follow the new shapes; resume generator reads `profile.tldr` from content. Verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build:resume-all` (both PDFs), SSR smoke marker sets per language incl. localized durations/companies/metrics/roles on home + `/experience` + project detail — deleted after the run. ⬜ Browser: VI pages show the localized timeline; `?edit` company/duration/role | | 19 | Localize the §4 structure-assigned strings (`experience.company` of non-company entries, `duration`, `currentInterests`, `roles`, `keywords`, `projects.role`/`metrics`) or keep them EN-only like `technologies` | post-v4 | ✅ Done 2026-10-22 (automated) — fields moved to the text documents (§4 follow-up); VI document carries localized values (numeric dates + "nay", "Sẵn sàng cho cơ hội mới", "Nghỉ giữa chặng", "Đã triển khai tại 16 sortations", "Xử lý 70.000 ảnh/tháng"), en overrides with the originals, proper nouns and term lists identical (en omits); company/duration/role inline-editable, tag arrays JSON-panel-only; templates in `draft.ts` and JsonPanel hints follow the new shapes; resume generator reads `profile.tldr` from content. Verified: `pnpm build`, `pnpm validate:content`, `pnpm lint` (no new warnings), `pnpm build:resume-all` (both PDFs), SSR smoke marker sets per language incl. localized durations/companies/metrics/roles on home + `/experience` + project detail — deleted after the run. ⬜ Browser: VI pages show the localized timeline; `?edit` company/duration/role |
| 20 | Save pipeline adapted to the live Gitea 28 Contents API | 3 | ✅ Done 2026-10-23 — the first real save answered 422 "repository file already exists [path: src/i18n/locales/vi/content.json]": Gitea 28 decides create-vs-update by the body `sha` (blob ID), which the client never sent. `draft.ts`: `fetchDoc`/`fetchTextFile` keep the blob `sha`; PUT bodies send `sha`; the new blob sha is read from the FileResponse `content.sha`; save conflict detection = 422 with a "does not match" message (412 kept for older deployments); §6.1 amended. Verified: `tsc -b`, `pnpm lint` (no new warnings), `scripts/smoke-draft.ts` 8/8. ⬜ Browser + Gitea: save → commit lands on the target branch; stale blob sha → conflict flow |
+39 -19
View File
@@ -1,7 +1,7 @@
// Draft store (spec-v4 §5.1, §5.5, §5.6, §6.1): the live branch documents // Draft store (spec-v4 §5.1, §5.5, §5.6, §6.1): the live branch documents
// fetched through the proxy, a copy-on-write draft over them, changed-path // fetched through the proxy, a copy-on-write draft over them, changed-path
// tracking, cross-document validation on every accepted edit, sessionStorage // tracking, cross-document validation on every accepted edit, sessionStorage
// durability, and the sequential-PUT save pipeline with last_commit_sha // durability, and the sequential-PUT save pipeline with blob-sha
// optimistic concurrency. Pure logic — the React glue lives in EditModeShell. // optimistic concurrency. Pure logic — the React glue lives in EditModeShell.
import contentEnJson from './locales/en/content.json'; import contentEnJson from './locales/en/content.json';
import contentViJson from './locales/vi/content.json'; import contentViJson from './locales/vi/content.json';
@@ -161,29 +161,38 @@ function encodeBase64(text: string): string {
export async function fetchDoc(file: string, branch: string): Promise<DocBase> { export async function fetchDoc(file: string, branch: string): Promise<DocBase> {
const res = await fetch(proxyUrl(file, branch)); const res = await fetch(proxyUrl(file, branch));
if (!res.ok) throw new Error(`GET ${file}: ${res.status}`); if (!res.ok) throw new Error(`GET ${file}: ${res.status}`);
const json = (await res.json()) as { content?: string; last_commit_sha?: string }; // The contents response carries both the blob sha (`sha`) and the last
// commit that touched the file (`last_commit_sha`). Gitea 28's UpdateFile
// concurrency field is the blob sha — that is the value the draft keeps.
const json = (await res.json()) as { content?: string; sha?: string };
return { return {
data: JSON.parse(decodeBase64(json.content ?? '')), data: JSON.parse(decodeBase64(json.content ?? '')),
sha: String(json.last_commit_sha ?? ''), sha: String(json.sha ?? ''),
}; };
} }
export async function fetchTextFile(file: string, branch: string): Promise<{ text: string; sha: string }> { export async function fetchTextFile(file: string, branch: string): Promise<{ text: string; sha: string }> {
const res = await fetch(proxyUrl(file, branch)); const res = await fetch(proxyUrl(file, branch));
if (!res.ok) throw new Error(`GET ${file}: ${res.status}`); if (!res.ok) throw new Error(`GET ${file}: ${res.status}`);
const json = (await res.json()) as { content?: string; last_commit_sha?: string }; const json = (await res.json()) as { content?: string; sha?: string };
return { text: decodeBase64(json.content ?? ''), sha: String(json.last_commit_sha ?? '') }; return { text: decodeBase64(json.content ?? ''), sha: String(json.sha ?? '') };
} }
export type PutResult = { ok: true; sha: string } | { ok: false; status: number }; export type PutResult =
| { ok: true; sha: string }
| { ok: false; status: number; message: string };
async function putBase64( async function putBase64(
file: string, file: string,
encoded: string, encoded: string,
message: string, message: string,
lastCommitSha: string, blobSha: string,
branch: string, branch: string,
): Promise<PutResult> { ): Promise<PutResult> {
// Gitea 28 UpdateFileOptions: `sha` is the blob ID of the file to update —
// empty means create (an existing file then answers 422 "repository file
// already exists"), a stale one means a concurrency mismatch. The FileResponse
// returns the new blob sha at `content.sha`.
const res = await fetch(proxyUrl(file, branch), { const res = await fetch(proxyUrl(file, branch), {
method: 'PUT', method: 'PUT',
headers: { 'content-type': 'application/json' }, headers: { 'content-type': 'application/json' },
@@ -191,12 +200,21 @@ async function putBase64(
content: encoded, content: encoded,
message, message,
branch, branch,
last_commit_sha: lastCommitSha, sha: blobSha,
}), }),
}); });
if (!res.ok) return { ok: false, status: res.status }; if (!res.ok) {
const json = (await res.json()) as { last_commit_sha?: string }; let detail = '';
return { ok: true, sha: String(json.last_commit_sha ?? '') }; try {
const json = (await res.json()) as { message?: string };
detail = String(json.message ?? '');
} catch {
// non-JSON body — the status code alone still drives the caller
}
return { ok: false, status: res.status, message: detail };
}
const json = (await res.json()) as { content?: { sha?: string } };
return { ok: true, sha: String(json.content?.sha ?? '') };
} }
// Serialize exactly as the repository file is formatted (2-space indent, key // Serialize exactly as the repository file is formatted (2-space indent, key
@@ -333,7 +351,7 @@ export function recordForTitlePath(
export class DraftStore { export class DraftStore {
private base = new Map<DraftDocId, DocBase>(); private base = new Map<DraftDocId, DocBase>();
// The baseline the draft was taken against. `base` may be refreshed by a // The baseline the draft was taken against. `base` may be refreshed by a
// 412 conflict; `origin` never moves until a document lands, so a rebase // 422/412 conflict; `origin` never moves until a document lands, so a rebase
// can always tell my changes from theirs (§5.6). // can always tell my changes from theirs (§5.6).
private origin = new Map<DraftDocId, unknown>(); private origin = new Map<DraftDocId, unknown>();
private working = new Map<DraftDocId, unknown>(); private working = new Map<DraftDocId, unknown>();
@@ -830,7 +848,7 @@ export class DraftStore {
} }
// Re-apply a persisted draft onto freshly fetched baselines. A document // Re-apply a persisted draft onto freshly fetched baselines. A document
// whose last_commit_sha moved since the draft was taken is returned as // whose blob sha moved since the draft was taken is returned as
// drifted → the conflict flow (§5.6) owns it from here. // drifted → the conflict flow (§5.6) owns it from here.
applySaved(saved: SavedDraft): DraftDocId[] { applySaved(saved: SavedDraft): DraftDocId[] {
this.created = new Set(saved.created ?? []); this.created = new Set(saved.created ?? []);
@@ -902,10 +920,12 @@ export type DocSaveResult = {
http?: number; http?: number;
}; };
// Sequential PUTs, one commit per touched document (§6.1). A 412 refreshes // Sequential PUTs, one commit per touched document (§6.1). A blob-sha
// that document's base and reports a conflict without stopping the sequence; // mismatch — Gitea 28 answers 422 with a "does not match" message, older
// any other failure stops so a retry resumes from the first unwritten // deployments answered 412 — refreshes that document's base and reports a
// document — landed documents are never rewritten (§5.6). // conflict without stopping the sequence; any other failure stops so a retry
// resumes from the first unwritten document — landed documents are never
// rewritten (§5.6).
export async function saveDraft( export async function saveDraft(
store: DraftStore, store: DraftStore,
onResult: (result: DocSaveResult) => void, onResult: (result: DocSaveResult) => void,
@@ -924,13 +944,13 @@ export async function saveDraft(
onResult(result); onResult(result);
continue; continue;
} }
if (res.status === 412) { if (res.status === 412 || (res.status === 422 && /does not match/i.test(res.message))) {
try { try {
store.resetBase(id, await fetchDoc(meta.file, branch)); store.resetBase(id, await fetchDoc(meta.file, branch));
} catch { } catch {
// keep the old base; the conflict UI still offers take-theirs // keep the old base; the conflict UI still offers take-theirs
} }
const result: DocSaveResult = { id, status: 'conflict', http: 412 }; const result: DocSaveResult = { id, status: 'conflict', http: res.status };
results.push(result); results.push(result);
onResult(result); onResult(result);
continue; continue;