oficina / mapa Public

Saving for the editor: the autosave reply, rebase, commit=1, no-op commits

Level-up §6.5 and §8, the store and its routes:

- POST …/draft answers {version, revision} and, when the draft's base
  is behind, a merge over exactly the text the request carried:
  {against, body}, {against, conflict, hunks[{at, count, base, mine,
  theirs}]}, {noBase} or {gone}. An unwritten day has none.
- rebase=R moves an existing draft's base, only from the current
  version and only to a revision of this live page inside the window;
  otherwise 409/422 and nothing moves. Draft writes are now
  compare-and-swap on the version they read.
- commit=1 writes the carried text as the draft and commits it in one
  request, only from the current version; with no body it commits the
  stored draft.
- A commit whose final body is the current body (plain, Merged,
  Resolve, a written day) writes no revision and no event, and drops
  the draft the tab held.
- Resolve answers {outcome, revision, body} when asked for JSON.
- MakeTeamPage takes the revision its block numbers index and refuses
  a stale one; the scriptless form carries the note's revision.
- POST /scratch with a 'first' token is a new scratch page's first
  autosave (D12): single-flight per person and token, held in memory
  only; ErrEmpty kept.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f5b54b581aa341b8b13afe5cc68a07b815155f11 parent 7e6a203
16 files changed, +602 −64
  • internal/mapa/app.go +2 −0
  • internal/mapa/autosave.go +128 −0
  • internal/mapa/commit.go +29 −5
  • internal/mapa/daily.go +19 −2
  • internal/mapa/daily_test.go +10 −5
  • internal/mapa/drafts.go +50 −16
  • internal/mapa/firstscratch.go +125 −0
  • internal/mapa/handlers_autosave.go +146 −0
  • internal/mapa/handlers_drafts.go +7 −26
  • internal/mapa/handlers_edit.go +37 −2
  • internal/mapa/private.go +7 −2
  • internal/mapa/share.go +13 −2
  • internal/mapa/templates/share.html +1 −0
  • internal/mapatest/daily_test.go +11 −2
  • internal/mapatest/gate8_test.go +15 −1
  • internal/mapatest/plaintext_scan_test.go +2 −1
diff --git a/internal/mapa/app.go b/internal/mapa/app.go
index cec72e3..7ec154a 100644
--- a/internal/mapa/app.go
+++ b/internal/mapa/app.go
@@ -28,6 +28,8 @@ type app struct {
auth *auth.Auth
logger *slog.Logger
routes chi.Router
+ // firsts is the new scratch pages' first-commit tokens (D12).
+ firsts firsts
// testIdentity and allowUnauthenticated let a test act as a person
// without a magic-link round trip. Only AppForTest sets them.
testIdentity string
diff --git a/internal/mapa/autosave.go b/internal/mapa/autosave.go
new file mode 100644
index 0000000..2806be9
--- /dev/null
+++ b/internal/mapa/autosave.go
@@ -0,0 +1,128 @@
+package mapa
+
+import (
+ "context"
+ "errors"
+
+ "gorm.io/gorm"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+)
+
+// The editor's autosave (level-up §6.5). An autosave writes the
+// person's draft and nothing else, and its reply tells the editor
+// whether a teammate's revision landed since the draft's base: the
+// merge of exactly the text the request carried. A rebase moves an
+// existing draft's base once the editor has taken that merge in. Every
+// write here is a draft write, exempt from gate 8 by name (§5).
+
+// DraftWrite is one autosave: the base a new draft starts from, the
+// draft version the tab holds (0 for none), and its text. Rebase, when
+// set, moves an existing draft's base to that revision of its page.
+type DraftWrite struct {
+ Base, Version int64
+ Body string
+ Rebase int64
+}
+
+// ErrRebase is a rebase the store refuses: no draft to move, or a
+// revision that is not this page's inside the history window. Nothing
+// is written.
+var ErrRebase = errors.New("mapa: that is not a revision of this page")
+
+// Autosaved is an autosave's answer: the draft's new version, the
+// page's current revision (0 for an unwritten day or a deleted page),
+// and Behind when the draft's base is not that revision.
+type Autosaved struct {
+ Version, Revision int64
+ Behind *Behind
+}
+
+// Behind is the merge an autosave's reply carries (level-up §6.5): a
+// clean merge's body, a conflict's hunks, no merge base, or a page that
+// was deleted.
+type Behind struct {
+ Against int64
+ Body string
+ Conflict bool
+ Hunks []markup.Hunk
+ NoBase bool
+ Gone bool
+}
+
+// Autosave writes the draft and says how it stands against the page.
+func (store *Store) Autosave(ctx context.Context, viewer Viewer,
+ key DraftKey, write DraftWrite) (Autosaved, error) {
+ row, err := store.saveDraft(ctx, viewer.Address, key, write)
+ if err != nil {
+ return Autosaved{}, err
+ }
+ saved := Autosaved{Version: row.Version}
+ if key.PageID == 0 {
+ return saved, nil
+ }
+ viewer.MemberID = row.PersonID
+ page, err := store.readable(ctx, viewer, key.PageID)
+ if errors.Is(err, ErrNotFound) {
+ saved.Behind = &Behind{Gone: true}
+ return saved, nil
+ }
+ if err != nil || row.BaseRevision == page.Revision {
+ saved.Revision = page.Revision
+ return saved, err
+ }
+ saved.Revision = page.Revision
+ saved.Behind, err = store.behind(ctx, page, row.BaseRevision,
+ cleanBody(write.Body))
+ return saved, err
+}
+
+// behind merges sent, the text an autosave carried, from base over the
+// page's current revision.
+func (store *Store) behind(ctx context.Context, page Page, base int64,
+ sent string) (*Behind, error) {
+ original, found, err := store.baseBody(ctx, page.ID, base)
+ if err != nil {
+ return nil, err
+ }
+ if !found {
+ return &Behind{NoBase: true}, nil
+ }
+ current, err := store.OpenPage(page)
+ if err != nil {
+ return nil, err
+ }
+ hunks, clean := markup.Merge3(original, sent, current.Body)
+ out := &Behind{Against: page.Revision}
+ if !clean {
+ out.Conflict, out.Hunks = true, hunks
+ return out, nil
+ }
+ merged, _ := markup.Settle(hunks, nil)
+ out.Body = cleanBody(merged)
+ return out, nil
+}
+
+// rebaseTo moves an existing draft's base to revision, which must be a
+// revision of the draft's own live page inside the history window.
+func (store *Store) rebaseTo(database *gorm.DB, row *Draft, found bool,
+ key DraftKey, revision int64) error {
+ if !found || key.PageID == 0 {
+ return ErrRebase
+ }
+ var held int64
+ err := database.Model(&Revision{}).
+ Joins("JOIN pages ON pages.id = revisions.page_id").
+ Where("revisions.page_id = ? AND revisions.revision = ? AND "+
+ "revisions.at > ? AND pages.gone = ?", key.PageID, revision,
+ store.now().UTC().Add(-HistoryWindow), false).
+ Count(&held).Error
+ if err != nil {
+ return err
+ }
+ if held == 0 {
+ return ErrRebase
+ }
+ row.BaseRevision = revision
+ return nil
+}
diff --git a/internal/mapa/commit.go b/internal/mapa/commit.go
index 4941cdb..7ac9808 100644
--- a/internal/mapa/commit.go
+++ b/internal/mapa/commit.go
@@ -69,6 +69,9 @@ func (store *Store) CommitFrom(ctx context.Context, who string, pageID,
record.Body); err != nil {
return err
}
+ if body == record.Body {
+ return errNoChange
+ }
record.Body = body
if stale {
outcome = Kept
@@ -77,10 +80,25 @@ func (store *Store) CommitFrom(ctx context.Context, who string, pageID,
}
return tx.commit(&page, record, actor, VerbEdited)
})
- if errors.Is(err, errUnmerged) && stale {
+ return store.afterCommitFrom(ctx, who, pageID, base, held, body,
+ outcome, stale, err)
+}
+
+// afterCommitFrom finishes a commit outside its transaction: a save
+// that could not merge keeps its text as the draft, and one that changed
+// nothing drops the draft the tab held, writing no revision and no
+// event (level-up §6.4, step 7).
+func (store *Store) afterCommitFrom(ctx context.Context, who string,
+ pageID, base, held int64, body string, outcome Outcome, stale bool,
+ err error) (Outcome, error) {
+ switch {
+ case errors.Is(err, errNoChange) && stale:
+ return Kept, nil
+ case errors.Is(err, errNoChange):
+ return outcome, store.dropHeldDraft(ctx, who, pageID, held)
+ case errors.Is(err, errUnmerged) && stale:
return outcome, ErrStaleTab
- }
- if errors.Is(err, errUnmerged) {
+ case errors.Is(err, errUnmerged):
return outcome, store.keepDraft(ctx, who, pageID, base, body)
}
return outcome, err
@@ -136,7 +154,7 @@ func (tx *Tx) merged(page Page, base int64, mine,
return Conflicted, mine, errUnmerged
}
settled, _ := markup.Settle(hunks, nil)
- return Merged, settled, nil
+ return Merged, cleanBody(settled), nil
}
// Resolve settles a conflict the person has chosen through: it commits
@@ -160,14 +178,20 @@ func (store *Store) Resolve(ctx context.Context, who string, pageID,
outcome = Conflicted
return errUnmerged
}
+ if cleanBody(body) == record.Body {
+ return errNoChange
+ }
record.Body = cleanBody(body)
if err := tx.dropDraft(actor, page.ID); err != nil {
return err
}
return tx.commit(&page, record, actor, VerbEdited)
})
- if errors.Is(err, errUnmerged) {
+ switch {
+ case errors.Is(err, errUnmerged):
return outcome, nil
+ case errors.Is(err, errNoChange):
+ return outcome, store.dropHeldDraft(ctx, who, pageID, held)
}
return outcome, err
}
diff --git a/internal/mapa/daily.go b/internal/mapa/daily.go
index 0f970a4..abb71f6 100644
--- a/internal/mapa/daily.go
+++ b/internal/mapa/daily.go
@@ -104,12 +104,29 @@ func (store *Store) SaveDailyFrom(ctx context.Context, who, date string,
if page.Revision != baseRevision {
return ErrStale
}
- return tx.commit(&page, Record{Date: date, Body: body}, actor,
- VerbEdited)
+ return tx.commitDay(&page, actor, date, body)
})
+ if errors.Is(err, errNoChange) {
+ return page, nil
+ }
return page, err
}
+// commitDay commits a written day's note, unless the body is already
+// what it says: a save that changes nothing writes nothing (level-up
+// §6.4, step 7).
+func (tx *Tx) commitDay(page *Page, actor int64, date, body string) error {
+ current, err := tx.store.OpenPage(*page)
+ if err != nil {
+ return err
+ }
+ if current.Body == body {
+ return errNoChange
+ }
+ return tx.commit(page, Record{Date: date, Body: body}, actor,
+ VerbEdited)
+}
+
func (tx *Tx) newDaily(actor int64, date string, baseRevision, held int64,
body string) (Page, error) {
if baseRevision != 0 {
diff --git a/internal/mapa/daily_test.go b/internal/mapa/daily_test.go
index 1e9df37..79b6530 100644
--- a/internal/mapa/daily_test.go
+++ b/internal/mapa/daily_test.go
@@ -79,7 +79,8 @@ func TestMakeTeamPageMovesTheChosenBlocksOnly(t *testing.T) {
note, _ := store.SaveDaily(ctx(), ana, "2026-11-12", 0,
"Private thought.\n\n- Acme renews in March\n- Ask Tom\n\nMore.")
before := loadPage(t, store, note.ID)
- shared, err := store.MakeTeamPage(ctx(), ana, note.ID, []int{1, 2},
+ shared, err := store.MakeTeamPage(ctx(), ana, note.ID,
+ note.Revision, []int{1, 2},
"Acme renewal")
if err != nil {
t.Fatal(err)
@@ -112,12 +113,14 @@ func TestGate2MakeTeamPageRefusesTakenAndDateTitles(t *testing.T) {
before := counts(t, store)
for title, want := range map[string]error{"ACME": ErrTitleTaken,
"2026-11-13": ErrTitleDate, "2026-11-13": ErrTitleDate} {
- if _, err := store.MakeTeamPage(ctx(), ana, note.ID, []int{0},
+ if _, err := store.MakeTeamPage(ctx(), ana, note.ID,
+ note.Revision, []int{0},
title); !errors.Is(err, want) {
t.Errorf("%q: %v", title, err)
}
}
- if _, err := store.MakeTeamPage(ctx(), ana, note.ID, nil,
+ if _, err := store.MakeTeamPage(ctx(), ana, note.ID,
+ note.Revision, nil,
"Fresh"); !errors.Is(err, ErrNothingChosen) {
t.Errorf("nothing chosen: %v", err)
}
@@ -130,12 +133,14 @@ func TestGate2MakeTeamPageRefusesTakenAndDateTitles(t *testing.T) {
func TestOnlyTheOwnerSharesAndOnlyPrivateNotes(t *testing.T) {
store := testStore(t)
note, _ := store.SaveDaily(ctx(), ana, "2026-11-12", 0, "a")
- if _, err := store.MakeTeamPage(ctx(), bo, note.ID, []int{0},
+ if _, err := store.MakeTeamPage(ctx(), bo, note.ID,
+ note.Revision, []int{0},
"Stolen"); !errors.Is(err, ErrNotFound) {
t.Fatalf("Bo shared Ana's note: %v", err)
}
team := mustCreate(t, store, "Team", "x")
- if _, err := store.MakeTeamPage(ctx(), ana, team.ID, []int{0},
+ if _, err := store.MakeTeamPage(ctx(), ana, team.ID,
+ team.Revision, []int{0},
"Again"); !errors.Is(err, ErrNotFound) {
t.Fatalf("a team page was shared again: %v", err)
}
diff --git a/internal/mapa/drafts.go b/internal/mapa/drafts.go
index 6d4dc74..ff17313 100644
--- a/internal/mapa/drafts.go
+++ b/internal/mapa/drafts.go
@@ -84,32 +84,53 @@ func (store *Store) OwnDraft(ctx context.Context, viewer Viewer,
// for none; a mismatch is ErrStaleTab. It returns the new version.
func (store *Store) SaveDraft(ctx context.Context, who string,
key DraftKey, base, version int64, body string) (int64, error) {
+ row, err := store.saveDraft(ctx, who, key, DraftWrite{Base: base,
+ Version: version, Body: body})
+ return row.Version, err
+}
+
+// saveDraft writes one autosave and returns the draft as stored. A
+// rebase moves an existing draft's base first (rebase.go).
+func (store *Store) saveDraft(ctx context.Context, who string,
+ key DraftKey, write DraftWrite) (Draft, error) {
person, err := store.ensureMember(ctx, who)
if err != nil {
- return 0, err
+ return Draft{}, err
}
database := store.database.WithContext(ctx)
row, found, err := store.draftRow(database, person, key)
if err != nil {
- return 0, err
+ return row, err
}
- if (found && row.Version != version) || (!found && version != 0) {
- return 0, ErrStaleTab
+ if (found && row.Version != write.Version) ||
+ (!found && write.Version != 0) {
+ return row, ErrStaleTab
}
if !found {
- row = Draft{PersonID: person, BaseRevision: base}
+ row = Draft{PersonID: person, BaseRevision: write.Base}
}
- return store.writeDraft(database, row, key, cleanBody(body))
+ if write.Rebase != 0 {
+ if err := store.rebaseTo(database, &row, found, key,
+ write.Rebase); err != nil {
+ return row, err
+ }
+ }
+ row.Version, err = store.writeDraft(database, row, key,
+ cleanBody(write.Body))
+ return row, err
}
-// writeDraft stores a draft's text under a fresh version. No event: this
-// is the exemption.
+// writeDraft stores a draft's text and base under a fresh version. An
+// existing row is written only if it still holds the version it was
+// read with: a write another tab made in between is never lost, and
+// this one is ErrStaleTab. No event: this is the exemption.
func (store *Store) writeDraft(database *gorm.DB, row Draft, key DraftKey,
body string) (int64, error) {
sealed, err := store.sealRecord(seal.PurposeDraft, Record{Body: body})
if err != nil {
return 0, err
}
+ held := row.Version
if row.Version, err = randomPositive(); err != nil {
return 0, err
}
@@ -120,8 +141,13 @@ func (store *Store) writeDraft(database *gorm.DB, row Draft, key DraftKey,
}
return row.Version, database.Create(&row).Error
}
- return row.Version, database.Model(&row).Select("Version",
- "SealedRecord", "UpdatedAt").Updates(&row).Error
+ written := database.Model(&row).Where("version = ?", held).
+ Select("Version", "SealedRecord", "UpdatedAt", "BaseRevision").
+ Updates(&row)
+ if written.Error == nil && written.RowsAffected == 0 {
+ return 0, ErrStaleTab
+ }
+ return row.Version, written.Error
}
func (store *Store) keyDraft(row *Draft, key DraftKey) error {
@@ -152,12 +178,6 @@ func (store *Store) keepDraft(ctx context.Context, who string, pageID,
row = Draft{PersonID: person}
}
row.BaseRevision = base
- if found {
- err = database.Model(&row).Update("base_revision", base).Error
- }
- if err != nil {
- return err
- }
_, err = store.writeDraft(database, row, key, body)
return err
}
@@ -179,6 +199,20 @@ func (store *Store) DiscardDraft(ctx context.Context, viewer Viewer,
return database.Delete(&row).Error
}
+// dropHeldDraft removes the person's draft on a page if it is still the
+// version the tab held: a commit that changed nothing ends the draft as
+// a commit would, and never a newer one another tab wrote. No event.
+func (store *Store) dropHeldDraft(ctx context.Context, who string,
+ pageID, held int64) error {
+ viewer, err := store.Viewer(ctx, who, nil)
+ if err != nil || viewer.MemberID == 0 || held == 0 {
+ return err
+ }
+ return store.database.WithContext(ctx).Where("person_id = ? AND "+
+ "page_id = ? AND version = ?", viewer.MemberID, pageID, held).
+ Delete(&Draft{}).Error
+}
+
// dropDraft removes the person's draft for a page inside a commit.
func (tx *Tx) dropDraft(person, pageID int64) error {
return tx.db.Where("person_id = ? AND page_id = ?", person, pageID).
diff --git a/internal/mapa/firstscratch.go b/internal/mapa/firstscratch.go
new file mode 100644
index 0000000..27339a9
--- /dev/null
+++ b/internal/mapa/firstscratch.go
@@ -0,0 +1,125 @@
+package mapa
+
+import (
+ "errors"
+ "net/http"
+ "regexp"
+ "sync"
+ "time"
+)
+
+// A new scratch page's first commit (level-up §6.5, D12). The editor on
+// New scratch page has no Save button, so its first autosave is the
+// save: a commit that creates the page, refused when empty (ErrEmpty),
+// and single-flight, so two quick autosaves create one page.
+//
+// The key is a token the tab draws once for the new page and sends as
+// "first" with every autosave until it learns the page's address. It is
+// held only here, in memory, for firstHold: never in the database, so
+// §4's plaintext list is unchanged. The first request with a token
+// creates the page; any later one with the same token, from the same
+// person, waits for it and is an autosave of a draft on that page
+// instead. A token forgotten (past firstHold, or by a restart) is a new
+// page, which only a tab that kept sending it for that long could meet.
+
+// firstHold is how long a token is remembered.
+const firstHold = 10 * time.Minute
+
+// firstCap bounds how many tokens are remembered at once.
+const firstCap = 4096
+
+var firstToken = regexp.MustCompile(`^[A-Za-z0-9_-]{16,64}$`)
+
+// firsts remembers which scratch page each first-commit token made.
+type firsts struct {
+ mutex sync.Mutex
+ made map[string]firstMade
+}
+
+type firstMade struct {
+ pageID, revision int64
+ public string
+ at time.Time
+}
+
+// recall is the page a token made, forgetting tokens past firstHold.
+// The caller holds the mutex.
+func (held *firsts) recall(key string, now time.Time) (firstMade, bool) {
+ if held.made == nil {
+ held.made = map[string]firstMade{}
+ }
+ for other, made := range held.made {
+ if now.Sub(made.at) > firstHold {
+ delete(held.made, other)
+ }
+ }
+ made, ok := held.made[key]
+ return made, ok
+}
+
+func (held *firsts) remember(key string, made firstMade) {
+ if len(held.made) < firstCap {
+ held.made[key] = made
+ }
+}
+
+// firstScratch is POST /scratch with a "first" token: the new page's
+// first autosave. It answers JSON: {href, page, revision} when it made
+// the page; when the page was already made, this is an autosave of a
+// draft on it, answered {href, page, version, revision, merge?}; and
+// 422 {empty: true} when there is nothing to save.
+func (app *app) firstScratch(writer http.ResponseWriter,
+ request *http.Request, token string) {
+ viewer, err := app.viewer(request)
+ if err != nil || !firstToken.MatchString(token) {
+ notFound(writer, request)
+ return
+ }
+ key := viewer.Address + "\x00" + token
+ app.firsts.mutex.Lock()
+ defer app.firsts.mutex.Unlock()
+ made, ok := app.firsts.recall(key, app.store.now())
+ if ok {
+ app.firstDraft(writer, request, viewer, made)
+ return
+ }
+ page, err := app.store.CreateScratch(request.Context(), viewer.Address,
+ request.PostFormValue("body"))
+ if errors.Is(err, ErrEmpty) {
+ writer.Header().Set("Content-Type", "application/json; charset=utf-8")
+ writer.WriteHeader(http.StatusUnprocessableEntity)
+ answer(writer, map[string]any{"empty": true})
+ return
+ }
+ if err != nil {
+ app.fail(writer, request, err)
+ return
+ }
+ made = firstMade{pageID: page.ID, revision: page.Revision,
+ public: publicID(page.Nonce), at: app.store.now()}
+ app.firsts.remember(key, made)
+ answer(writer, map[string]any{"href": PagePath(page),
+ "page": made.public, "revision": idText(page.Revision)})
+}
+
+// firstDraft is a later autosave carrying a token whose page exists: a
+// draft on that page, based on its first revision, answered as any
+// autosave is, with the page's address.
+func (app *app) firstDraft(writer http.ResponseWriter,
+ request *http.Request, viewer Viewer, made firstMade) {
+ key := DraftKey{PageID: made.pageID}
+ saved, err := app.store.Autosave(request.Context(), viewer, key,
+ DraftWrite{Base: made.revision, Version: formInt(request, "version"),
+ Body: request.PostFormValue("body")})
+ if errors.Is(err, ErrStaleTab) {
+ app.staleTab(writer, request, key)
+ return
+ }
+ if err != nil {
+ app.fail(writer, request, err)
+ return
+ }
+ reply := autosaveReply(saved)
+ reply["href"], reply["page"] = "/p/"+made.public, made.public
+ answer(writer, reply)
+}
diff --git a/internal/mapa/handlers_autosave.go b/internal/mapa/handlers_autosave.go
new file mode 100644
index 0000000..b33706a
--- /dev/null
+++ b/internal/mapa/handlers_autosave.go
@@ -0,0 +1,146 @@
+package mapa
+
+import (
+ "errors"
+ "net/http"
+ "strconv"
+
+ "amadan.net/oficina/mapa/internal/mapa/markup"
+)
+
+// POST …/draft, the editor's autosave (level-up §6.5, §8). With base,
+// version and body it writes the person's draft and answers
+//
+// {version, revision, merge?}
+//
+// where merge, present when the draft's base is not the page's current
+// revision, is computed over exactly the text this request carried:
+//
+// {against, body} the merge is clean
+// {against, conflict: true, hunks} each {at, count, base, mine, theirs}
+// {noBase: true} the base is past the window
+// {gone: true} the page was deleted
+//
+// rebase=R also moves an existing draft's base to R, if version is
+// current and R is a revision of this page inside the window; anything
+// else is refused (409 stale, 422 {refused: "rebase"}) and moves
+// nothing. commit=1 writes the draft (when body is sent) and commits it
+// in one request, only from the current version. It never touches the
+// page or its revision except through that commit (gate 11).
+
+func (app *app) autosave(writer http.ResponseWriter, request *http.Request) {
+ viewer, err := app.viewer(request)
+ key, ok := app.draftKey(request, viewer)
+ if err != nil || !ok || !app.mayDraft(request, viewer, key) {
+ notFound(writer, request)
+ return
+ }
+ if request.PostFormValue("commit") == "1" {
+ app.commitNow(writer, request, viewer, key)
+ return
+ }
+ saved, err := app.store.Autosave(request.Context(), viewer, key,
+ DraftWrite{Base: formInt(request, "base"),
+ Version: formInt(request, "version"),
+ Body: request.PostFormValue("body"),
+ Rebase: formInt(request, "rebase")})
+ switch {
+ case errors.Is(err, ErrStaleTab):
+ app.staleTab(writer, request, key)
+ case errors.Is(err, ErrRebase):
+ refuseJSON(writer, http.StatusUnprocessableEntity, "rebase")
+ case err != nil:
+ app.fail(writer, request, err)
+ default:
+ answer(writer, autosaveReply(saved))
+ }
+}
+
+// refuseJSON answers the script that nothing was done, and why.
+func refuseJSON(writer http.ResponseWriter, status int, why string) {
+ writer.Header().Set("Content-Type", "application/json; charset=utf-8")
+ writer.Header().Set("Cache-Control", "no-store")
+ writer.WriteHeader(status)
+ answer(writer, map[string]any{"refused": why})
+}
+
+// autosaveReply is an autosave's JSON. Revisions and versions are
+// int63s, past what a JavaScript number holds, so they travel as text.
+func autosaveReply(saved Autosaved) map[string]any {
+ reply := map[string]any{"version": idText(saved.Version)}
+ if saved.Revision != 0 {
+ reply["revision"] = idText(saved.Revision)
+ }
+ if saved.Behind != nil {
+ reply["merge"] = mergeReply(*saved.Behind)
+ }
+ return reply
+}
+
+func mergeReply(behind Behind) map[string]any {
+ switch {
+ case behind.Gone:
+ return map[string]any{"gone": true}
+ case behind.NoBase:
+ return map[string]any{"noBase": true}
+ case !behind.Conflict:
+ return map[string]any{"against": idText(behind.Against),
+ "body": behind.Body}
+ }
+ return map[string]any{"against": idText(behind.Against),
+ "conflict": true, "hunks": hunkReplies(behind.Hunks)}
+}
+
+// hunkReply is one conflicting hunk: at and count are its blocks in the
+// text the request carried, and base, mine and theirs the Markdown of
+// its three sides.
+type hunkReply struct {
+ At int `json:"at"`
+ Count int `json:"count"`
+ Base string `json:"base"`
+ Mine string `json:"mine"`
+ Theirs string `json:"theirs"`
+}
+
+func hunkReplies(hunks []markup.Hunk) []hunkReply {
+ out := []hunkReply{}
+ for _, hunk := range hunks {
+ if !hunk.Conflict {
+ continue
+ }
+ base, mine, theirs := hunk.Sources()
+ out = append(out, hunkReply{At: hunk.MineAt, Count: len(hunk.Mine),
+ Base: base, Mine: mine, Theirs: theirs})
+ }
+ return out
+}
+
+func idText(value int64) string { return strconv.FormatInt(value, 10) }
+
+// commitNow is commit=1: the closing tab's one keepalive POST (D3). It
+// writes the text it carries as the draft and commits it, only if
+// version is the current draft's; otherwise it writes and commits
+// nothing. Past the keepalive cap the tab sends no body, and the draft
+// as last autosaved is committed.
+func (app *app) commitNow(writer http.ResponseWriter, request *http.Request,
+ viewer Viewer, key DraftKey) {
+ version := formInt(request, "version")
+ if _, sent := request.PostForm["body"]; sent {
+ saved, err := app.store.SaveDraft(request.Context(), viewer.Address,
+ key, formInt(request, "base"), version,
+ request.PostFormValue("body"))
+ if errors.Is(err, ErrStaleTab) {
+ app.staleTab(writer, request, key)
+ return
+ }
+ if err != nil {
+ app.fail(writer, request, err)
+ return
+ }
+ version = saved
+ } else if version == 0 {
+ app.staleTab(writer, request, key)
+ return
+ }
+ app.commitDraft(writer, request, viewer, key, version)
+}
diff --git a/internal/mapa/handlers_drafts.go b/internal/mapa/handlers_drafts.go
index 73ab7f2..a6d0b63 100644
--- a/internal/mapa/handlers_drafts.go
+++ b/internal/mapa/handlers_drafts.go
@@ -44,31 +44,6 @@ func (app *app) draftKey(request *http.Request,
return DraftKey{Date: date}, err == nil
}
-// autosave writes the person's draft. It never touches the page, its
-// body or its revision (gate 11). A stale tab is told, with the newer
-// draft to load.
-func (app *app) autosave(writer http.ResponseWriter, request *http.Request) {
- viewer, err := app.viewer(request)
- key, ok := app.draftKey(request, viewer)
- if err != nil || !ok || !app.mayDraft(request, viewer, key) {
- notFound(writer, request)
- return
- }
- base := formInt(request, "base")
- version, err := app.store.SaveDraft(request.Context(), viewer.Address,
- key, base, formInt(request, "version"),
- request.PostFormValue("body"))
- if errors.Is(err, ErrStaleTab) {
- app.staleTab(writer, request, key)
- return
- }
- if err != nil {
- app.fail(writer, request, err)
- return
- }
- answer(writer, map[string]any{"version": strconv.FormatInt(version, 10)})
-}
-
// mayDraft reports whether the viewer may touch a draft for the page:
// one they may open, or a deleted page they have a draft on. Anything
// else is answered as a page that is not there, so a page someone else
@@ -119,8 +94,14 @@ func (app *app) saveDraft(writer http.ResponseWriter,
notFound(writer, request)
return
}
+ app.commitDraft(writer, request, viewer, key, formInt(request, "version"))
+}
+
+// commitDraft commits the viewer's draft at version and answers.
+func (app *app) commitDraft(writer http.ResponseWriter,
+ request *http.Request, viewer Viewer, key DraftKey, version int64) {
outcome, pageID, err := app.store.CommitDraft(request.Context(), viewer,
- key, formInt(request, "version"))
+ key, version)
switch {
case errors.Is(err, ErrStaleTab):
app.staleTab(writer, request, key)
diff --git a/internal/mapa/handlers_edit.go b/internal/mapa/handlers_edit.go
index 4c8660f..01001a6 100644
--- a/internal/mapa/handlers_edit.go
+++ b/internal/mapa/handlers_edit.go
@@ -172,7 +172,7 @@ func (app *app) resolve(writer http.ResponseWriter, request *http.Request) {
}
body, keep, err := app.chosen(request, viewer, page.ID)
if errors.Is(err, errUnchosen) {
- seeOther(writer, request, pageHref(page.Public, "")+"/conflict")
+ app.afterResolve(writer, request, page, Conflicted, nil)
return
}
if err != nil {
@@ -214,11 +214,46 @@ func (app *app) linkMention(writer http.ResponseWriter,
seeOther(writer, request, pageHref(target.Public, "linked"))
}
+// afterResolve answers a choice: the form is sent on to the page, or to
+// the conflict again; the editor, asking for JSON, gets
+// {outcome, revision, body}, the page as it now stands (level-up §6.5).
func (app *app) afterResolve(writer http.ResponseWriter,
request *http.Request, page PageView, outcome Outcome, err error) {
if err != nil {
app.refuse(writer, request, err)
return
}
- seeOther(writer, request, afterSave(page.Href, page.Public, outcome))
+ if !wantsJSON(request) {
+ seeOther(writer, request, afterSave(page.Href, page.Public, outcome))
+ return
+ }
+ viewer, err := app.viewer(request)
+ current := page
+ if err == nil {
+ current, err = app.index.View(request.Context(), ScopeOf(viewer),
+ page.ID)
+ }
+ if err != nil {
+ app.refuse(writer, request, err)
+ return
+ }
+ answer(writer, map[string]any{"outcome": outcomeName(outcome),
+ "revision": idText(current.Revision), "body": current.Body})
+}
+
+// outcomeName is an outcome as the script reads it.
+func outcomeName(outcome Outcome) string {
+ switch outcome {
+ case Saved:
+ return "saved"
+ case Merged:
+ return "merged"
+ case Conflicted:
+ return "conflicted"
+ case NoBase:
+ return "noBase"
+ case Kept:
+ return "kept"
+ }
+ return ""
}
diff --git a/internal/mapa/private.go b/internal/mapa/private.go
index 7a9badc..bfc63ba 100644
--- a/internal/mapa/private.go
+++ b/internal/mapa/private.go
@@ -48,6 +48,10 @@ func (app *app) newScratch(writer http.ResponseWriter,
func (app *app) createScratch(writer http.ResponseWriter,
request *http.Request) {
+ if token := request.PostFormValue("first"); token != "" {
+ app.firstScratch(writer, request, token)
+ return
+ }
address, _ := app.identity(request)
body := request.PostFormValue("body")
page, err := app.store.CreateScratch(request.Context(), address, body)
@@ -117,8 +121,9 @@ func (app *app) share(writer http.ResponseWriter, request *http.Request) {
}
address, _ := app.identity(request)
shared, err := app.store.MakeTeamPage(request.Context(), address,
- ref.ID, chosen, data.Title)
- if sayable(err) || errors.Is(err, ErrNothingChosen) {
+ ref.ID, formInt(request, "revision"), chosen, data.Title)
+ if sayable(err) || errors.Is(err, ErrNothingChosen) ||
+ errors.Is(err, ErrNoteChanged) {
data.Error = err.Error()
data.Taken = app.index.TitleHref(request.Context(), data.Title)
app.showShare(writer, request, http.StatusUnprocessableEntity, data)
diff --git a/internal/mapa/share.go b/internal/mapa/share.go
index 14e811a..114e595 100644
--- a/internal/mapa/share.go
+++ b/internal/mapa/share.go
@@ -12,14 +12,22 @@ import (
// ErrNothingChosen is "Make team page" with no blocks selected.
var ErrNothingChosen = errors.New("Choose at least one block to share.")
+// ErrNoteChanged is "Make team page" over a revision that is no longer
+// the note's: the chosen block numbers named that revision's blocks, so
+// they are not used (level-up §6.7).
+var ErrNoteChanged = errors.New("Your note changed since these blocks " +
+ "were shown. Choose them again.")
+
// MakeTeamPage shares private writing (§3.4, decision 8): the chosen
// blocks of one of who's daily or scratch notes become a NEW team page,
// at its first revision, and the note gets a link to it in their place.
// The note itself is never re-ruled, so no private-era revision ever
// becomes team-readable. A taken or date-shaped title asks for another
-// (gate 2).
+// (gate 2). revision is the note's revision the block numbers index;
+// a stale one is refused with ErrNoteChanged and nothing is written.
func (store *Store) MakeTeamPage(ctx context.Context, who string,
- sourceID int64, chosen []int, rawTitle string) (Page, error) {
+ sourceID, revision int64, chosen []int, rawTitle string) (Page,
+ error) {
title, err := CleanTitle(rawTitle)
if err != nil {
return Page{}, err
@@ -34,6 +42,9 @@ func (store *Store) MakeTeamPage(ctx context.Context, who string,
if err != nil || source.Rung != RungPrivate {
return errors.Join(ErrNotFound, err)
}
+ if source.Revision != revision {
+ return ErrNoteChanged
+ }
record, err := store.OpenPage(source)
if err != nil {
return err
diff --git a/internal/mapa/templates/share.html b/internal/mapa/templates/share.html
index f404380..744366e 100644
--- a/internal/mapa/templates/share.html
+++ b/internal/mapa/templates/share.html
@@ -2,6 +2,7 @@
{{template "back-nav" dict "Href" $d.Page.Href "Label" $d.Page.Label}}
{{template "page-header" dict "Title" "Make team page" "Sub" "The blocks you choose become a new team page that everyone in the team can open. Your note keeps a link to it in their place, and stays yours."}}
<form rst-form method="post" action="{{$d.Action}}">
+<input type="hidden" name="revision" value="{{$d.Page.Revision}}">
{{template "field-text" dict "Name" "title" "Label" "Title of the new page" "Value" $d.Title "Error" $d.Error "Required" true}}
{{with $d.Taken}}<p mapa-meta><a href="{{.}}">Open the page with that title</a></p>{{end}}
<fieldset mapa-choose>
diff --git a/internal/mapatest/daily_test.go b/internal/mapatest/daily_test.go
index d573b56..0f786a9 100644
--- a/internal/mapatest/daily_test.go
+++ b/internal/mapatest/daily_test.go
@@ -113,7 +113,8 @@ func TestMakeTeamPageFromADailyNote(t *testing.T) {
t.Fatal("the share form offers no blocks")
}
made := rig.post(t, Ana, "/p/"+share+"/share",
- url.Values{"title": {"Known"}, "block": {"1"}})
+ url.Values{"title": {"Known"}, "block": {"1"},
+ "revision": {formRevision(form)}})
if made.Code != http.StatusSeeOther {
t.Fatalf("share: %d", made.Code)
}
@@ -121,8 +122,10 @@ func TestMakeTeamPageFromADailyNote(t *testing.T) {
"The team should know this.") {
t.Fatal("Bo cannot read the shared page")
}
+ again := rig.page(t, Ana, "/p/"+share+"/share")
taken := rig.post(t, Ana, "/p/"+share+"/share",
- url.Values{"title": {"known"}, "block": {"0"}})
+ url.Values{"title": {"known"}, "block": {"0"},
+ "revision": {formRevision(again)}})
if taken.Code != http.StatusUnprocessableEntity ||
!strings.Contains(taken.Body.String(), `value="0" checked`) {
t.Fatal("a taken title must ask again, keeping the choice")
@@ -157,3 +160,9 @@ func TestAPrivatePageIsNotThereForAnyoneElse(t *testing.T) {
}
}
}
+
+// formRevision is the revision a form names: the one its blocks or its
+// text were drawn from.
+func formRevision(form string) string {
+ return between(form, `name="revision" value="`, `"`)
+}
diff --git a/internal/mapatest/gate8_test.go b/internal/mapatest/gate8_test.go
index 2a95fa7..0d3016b 100644
--- a/internal/mapatest/gate8_test.go
+++ b/internal/mapatest/gate8_test.go
@@ -165,9 +165,23 @@ func gate8Later(t *testing.T, acme, notes string) []step {
{route: "POST /p/{id}/share", do: func(rig *rig) *http.Response {
day := rig.page(t, Ana, "/d/2026-11-12")
note := between(day, `href="/p/`, `/share"`)
+ form := rig.page(t, Ana, "/p/"+note+"/share")
return rig.send(Ana, http.MethodPost, "/p/"+note+"/share",
- url.Values{"title": {"Shared"}, "block": {"0"}})
+ url.Values{"title": {"Shared"}, "block": {"0"},
+ "revision": {formRevision(form)}})
}},
+ // The closing tab's commit=1, and a new scratch page's first
+ // autosave (level-up §6.5, D12): each a commit, with its event.
+ {route: "POST /p/{id}/draft", do: func(rig *rig) *http.Response {
+ _, reply := rig.autosave(t, Ana, acme, revisionOf(t, rig, acme),
+ "0", "Closing.")
+ version, _ := reply["version"].(string)
+ return rig.send(Ana, http.MethodPost, acme+"/draft",
+ url.Values{"commit": {"1"}, "version": {version},
+ "body": {"Closed."}})
+ }},
+ posting("/scratch", Ana, "/scratch", url.Values{
+ "first": {"gate-eight-token-0001"}, "body": {"First."}}),
{route: "POST /p/{id}/draft/scratch",
do: func(rig *rig) *http.Response {
rig.autosave(t, Ana, acme, revisionOf(t, rig, acme), "0", "E.")
diff --git a/internal/mapatest/plaintext_scan_test.go b/internal/mapatest/plaintext_scan_test.go
index 7abac2d..29b2e48 100644
--- a/internal/mapatest/plaintext_scan_test.go
+++ b/internal/mapatest/plaintext_scan_test.go
@@ -56,7 +56,8 @@ func writeEverything(t *testing.T, store *mapa.Store, index *mapa.Index) {
must(err)
_, err = store.CreateScratch(ctx, Ana, "scratchpad musing")
must(err)
- _, err = store.MakeTeamPage(ctx, Ana, daily.ID, []int{1}, "Sharedtitle")
+ _, err = store.MakeTeamPage(ctx, Ana, daily.ID, daily.Revision,
+ []int{1}, "Sharedtitle")
must(err)
writeLater(t, store, index)
}