Fix session loss, stale collab access and lossy restores

- Start-up keeps the saved session while the server is unreachable and
  retries the refresh; only a 4xx from the server signs the user out.
- Rooms of deleted pages are dropped (on purge, or when a write fails and
  the page is gone) instead of retrying their save every second.
- Trashing or restoring a page reconnects its editors (close code 4409),
  and open connections recheck access every 30 s; the editor reloads the
  page and reopens the document with its new rights.
- Restoring a version or replacing content first keeps unversioned
  changes as a "before-restore"/"before-replace" version; whether the
  saved document has a version is now worked out when a room loads.
- Destroying the collab provider no longer recurses through awareness
  listeners, which overflowed the stack on a 4409 close.
- Caret name labels are hidden from assistive tech.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tajniak81andClaude Opus 5.5 committed 2026-10-31 12:11:21 +01:00
1 parent 5e1dcf4291
commit 5fce899524
14 files changed
+404 -46

No files matched your search

+19 -1
View File
@@ -33,12 +33,30 @@ export function docwellExtensions(opts: ExtensionOptions = {}): AnyExtension[] {
if (opts.collab) {
list.push(
Collaboration.configure({ document: opts.collab.provider.doc }),
CollaborationCaret.configure({ provider: opts.collab.provider, user: opts.collab.user }),
CollaborationCaret.configure({ provider: opts.collab.provider, user: opts.collab.user, render: renderCaret }),
);
}
return list;
}
/**
* Another editor's caret with their name. The name is hidden from assistive
* tech, which would otherwise read it as part of the text.
*/
function renderCaret(user: Record<string, unknown>): HTMLElement {
const color = typeof user.color === "string" && /^#[0-9a-f]{3,8}$/i.test(user.color) ? user.color : "#888";
const caret = document.createElement("span");
caret.classList.add("collaboration-carets__caret");
caret.style.borderColor = color;
const label = document.createElement("div");
label.classList.add("collaboration-carets__label");
label.setAttribute("aria-hidden", "true");
label.style.backgroundColor = color;
label.textContent = typeof user.name === "string" ? user.name : "";
caret.append(label);
return caret;
}
/** A stable caret colour for a user id, from the design system's accent hues. */
export function userColor(id: string): string {
const hues = ["#2f7d6d", "#7c5cc4", "#c2571a", "#2f6fbf", "#b8327a", "#5f8a1f", "#a0761c", "#1f8a9a"];
+16 -1
View File
@@ -10,8 +10,15 @@ const MSG_AWARENESS = 1;
/** Close codes docwell-server uses when it refuses a page (see httpapi/collab.go). */
const CLOSE_UNAUTHORIZED = 4401;
const CLOSE_NOT_FOUND = 4404;
const CLOSE_ACCESS_CHANGED = 4409;
export type CollabStatus = "connecting" | "connected" | "offline" | "denied";
/**
* "changed": the server ended the session because the user's rights or the
* page changed (trashed, restored, role edited). The provider stops; the app
* should reload the page and open a new provider, so local edits the server
* would refuse are not kept.
*/
export type CollabStatus = "connecting" | "connected" | "offline" | "denied" | "changed";
export interface CollabProviderOptions {
/** WebSocket URL of docwell-server's /collab endpoint. */
@@ -53,8 +60,12 @@ export class CollabProvider {
return () => this.listeners.delete(fn);
}
/** Disconnects and frees the document. Safe to call again, also from a listener. */
destroy() {
if (this.destroyed) return;
this.destroyed = true;
// Listeners would otherwise hear the awareness changes made below.
this.listeners.clear();
clearTimeout(this.retryTimer);
window.removeEventListener("beforeunload", this.onUnload);
// Tell the others our cursor is gone before closing.
@@ -99,6 +110,10 @@ export class CollabProvider {
this.set("denied", false);
return;
}
if (e.code === CLOSE_ACCESS_CHANGED) {
this.set("changed");
return;
}
this.set("offline");
// 1 s, 2 s, 4 s … up to 30 s.
this.retryTimer = setTimeout(() => this.connect(), Math.min(1000 * 2 ** this.retries++, 30_000));
+103 -8
View File
@@ -75,8 +75,19 @@ func (h *Hub) Close(ctx context.Context) error {
// false when the peer cannot keep up and is being disconnected.
type Peer interface {
Send(msg []byte) bool
// Close disconnects the peer with a WebSocket close code.
Close(code int, reason string)
}
// Close codes sent to peers (the editor reacts to them).
const (
// CloseAccessChanged asks the peer to reload the page and reconnect: its
// rights changed, or the page was trashed or restored.
CloseAccessChanged = 4409
// CloseGone means the page no longer exists.
CloseGone = 4404
)
type room struct {
h *Hub
page string
@@ -150,6 +161,7 @@ func (r *room) load(ctx context.Context) error {
return err
}
r.lastVer = stored.LastVersion
r.unversion = stored.Unversioned
r.flushed = stored.UpdateIDs
var parts [][]byte
if stored.Snapshot != nil {
@@ -165,7 +177,7 @@ func (r *room) load(ctx context.Context) error {
}
parts = [][]byte{seed}
r.unflushed = [][]byte{seed}
r.dirty = true
r.dirty, r.unversion = true, true
}
if r.snapshot, err = o.Docs.Compact(ctx, parts); err != nil {
return err
@@ -211,6 +223,10 @@ func (r *room) tick(final bool) bool {
defer cancel()
r.mu.Lock()
if r.closed { // dropped by Drop
r.mu.Unlock()
return true
}
batch := r.unflushed
r.unflushed = nil
r.mu.Unlock()
@@ -220,6 +236,9 @@ func (r *room) tick(final bool) bool {
if err == nil {
id, err = o.Store.AppendUpdate(ctx, r.page, merged)
}
if err != nil && r.gone(ctx) {
return true
}
r.mu.Lock()
if err != nil {
o.Log.Error("collab: flush updates", "page", r.page, "err", err)
@@ -232,10 +251,14 @@ func (r *room) tick(final bool) bool {
r.mu.Lock()
empty := len(r.sessions) == 0
failed := false
if r.dirty && (final || empty || time.Since(r.lastEdit) >= o.IdleCompact || len(r.pending) >= 200) {
r.persistLocked(ctx, final || empty)
failed = !r.persistLocked(ctx, final || empty)
}
r.mu.Unlock()
if failed && r.gone(ctx) {
return true
}
if final {
return true
@@ -246,20 +269,34 @@ func (r *room) tick(final bool) bool {
defer r.mu.Unlock()
if len(r.sessions) == 0 && !r.dirty && len(r.unflushed) == 0 {
r.closed = true
delete(r.h.rooms, r.page)
if r.h.rooms[r.page] == r {
delete(r.h.rooms, r.page)
}
return true
}
return false
}
// gone checks, after a failed write, whether the page was deleted (directly
// or with its space or workspace). If so the room is dropped and its peers
// disconnected, instead of retrying forever.
func (r *room) gone(ctx context.Context) bool {
if _, err := r.h.o.Store.Content(ctx, r.page); !errors.Is(err, ErrNotFound) {
return false
}
r.h.Drop(r.page)
return true
}
// persistLocked saves the compacted snapshot, its derived content and, when
// due, a version. It releases r.mu while talking to the database.
func (r *room) persistLocked(ctx context.Context, leaving bool) {
// due, a version. It releases r.mu while talking to the database, and
// reports whether the save worked.
func (r *room) persistLocked(ctx context.Context, leaving bool) bool {
o := r.h.o
state, err := r.compactLocked(ctx)
if err != nil {
o.Log.Error("collab: compact", "page", r.page, "err", err)
return
return false
}
snap := Snapshot{State: state, LastEditor: r.editor, Covers: r.flushed}
// Unflushed updates are part of state, so they need no record of their own.
@@ -289,7 +326,9 @@ func (r *room) persistLocked(ctx context.Context, leaving bool) {
r.unflushed = append([][]byte{state}, r.unflushed...)
r.flushed = append(snap.Covers, r.flushed...)
r.unversion = r.unversion || version
return false
}
return true
}
// compactLocked folds pending updates into the snapshot (in memory only).
@@ -475,9 +514,27 @@ func (s *Session) Leave() {
func isEmptyUpdate(u []byte) bool { return len(u) == 2 && u[0] == 0 && u[1] == 0 }
// Replace replaces the page's document with ProseMirror JSON as an edit by
// user, so connected editors see it like any other change.
func (h *Hub) Replace(ctx context.Context, page, user string, doc json.RawMessage) error {
// user, so connected editors see it like any other change. Changes made since
// the last version are first kept as a version named label (a code the UI
// translates, e.g. "before-restore"), so a restore or
// import never loses them.
func (h *Hub) Replace(ctx context.Context, page, user string, doc json.RawMessage, label string) error {
return h.withRoom(ctx, page, func(r *room) error {
if r.unversion {
state, err := r.compactLocked(ctx)
if err != nil {
return err
}
read, err := h.o.Docs.Read(ctx, state)
if err != nil {
return err
}
snap := Snapshot{State: state, JSON: read.JSON, Text: read.Text, LastEditor: r.editor, Label: label}
if err := h.o.Store.AddVersion(ctx, page, snap); err != nil {
return err
}
r.unversion, r.lastVer = false, time.Now()
}
update, err := h.o.Docs.Replace(ctx, append([][]byte{r.snapshot}, r.pending...), doc)
if err != nil {
return err
@@ -487,6 +544,44 @@ func (h *Hub) Replace(ctx context.Context, page, user string, doc json.RawMessag
})
}
// Kick disconnects everyone on the page with CloseAccessChanged, so their
// editors reconnect with fresh rights (after the page was trashed or restored).
func (h *Hub) Kick(page string) {
h.mu.Lock()
r := h.rooms[page]
h.mu.Unlock()
if r == nil {
return
}
r.mu.Lock()
defer r.mu.Unlock()
for s := range r.sessions {
s.peer.Close(CloseAccessChanged, "access changed")
}
}
// Drop discards the page's room without saving and disconnects its peers:
// the page was deleted.
func (h *Hub) Drop(page string) {
h.mu.Lock()
r := h.rooms[page]
if r != nil {
delete(h.rooms, page)
}
h.mu.Unlock()
if r == nil {
return
}
<-r.ready
r.mu.Lock()
defer r.mu.Unlock()
r.closed = true
for s := range r.sessions {
s.peer.Close(CloseGone, "page deleted")
}
r.sessions = map[*Session]struct{}{}
}
// Content returns the page's current document as ProseMirror JSON: live from
// an open room, otherwise as last saved.
func (h *Hub) Content(ctx context.Context, page string) (json.RawMessage, error) {
+84 -4
View File
@@ -3,6 +3,7 @@ package collab
import (
"context"
"encoding/json"
"errors"
"strings"
"sync"
"testing"
@@ -17,10 +18,14 @@ type memStore struct {
updates map[string][][]byte
content map[string]json.RawMessage
versions map[string][]Snapshot
deleted map[string]bool
}
func newMemStore() *memStore {
return &memStore{snapshot: map[string][]byte{}, updates: map[string][][]byte{}, content: map[string]json.RawMessage{}, versions: map[string][]Snapshot{}}
return &memStore{
snapshot: map[string][]byte{}, updates: map[string][][]byte{}, content: map[string]json.RawMessage{},
versions: map[string][]Snapshot{}, deleted: map[string]bool{},
}
}
func (m *memStore) Load(_ context.Context, page string) (Stored, error) {
@@ -33,9 +38,14 @@ func (m *memStore) Load(_ context.Context, page string) (Stored, error) {
return s, nil
}
var errBadRelation = errors.New("page relation is invalid")
func (m *memStore) AppendUpdate(_ context.Context, page string, u []byte) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.deleted[page] {
return "", errBadRelation
}
m.updates[page] = append(m.updates[page], u)
return "u", nil
}
@@ -57,6 +67,9 @@ func (m *memStore) AddVersion(_ context.Context, page string, s Snapshot) error
func (m *memStore) Content(_ context.Context, page string) (json.RawMessage, error) {
m.mu.Lock()
defer m.mu.Unlock()
if m.deleted[page] {
return nil, ErrNotFound
}
return nullIfEmpty(m.content[page]), nil
}
@@ -68,8 +81,21 @@ func (m *memStore) VersionContent(context.Context, string, string) (json.RawMess
// fakePeer collects what the hub sends it.
type fakePeer struct {
mu sync.Mutex
msgs [][]byte
mu sync.Mutex
msgs [][]byte
closed int // close code, 0 while open
}
func (p *fakePeer) Close(code int, _ string) {
p.mu.Lock()
defer p.mu.Unlock()
p.closed = code
}
func (p *fakePeer) closeCode() int {
p.mu.Lock()
defer p.mu.Unlock()
return p.closed
}
func (p *fakePeer) Send(msg []byte) bool {
@@ -263,12 +289,16 @@ func TestSeedFromJSONAndReplace(t *testing.T) {
}
// A REST replace reaches connected peers as an ordinary update.
if err := h.Replace(ctx, "p2", "bob", docJSON("restored")); err != nil {
if err := h.Replace(ctx, "p2", "bob", docJSON("restored"), "before-restore"); err != nil {
t.Fatal(err)
}
if got := peer.take(msgSync, syncUpdate); len(got) != 1 {
t.Fatal("replace not relayed")
}
// The seeded text had no version yet, so the replace kept one first.
if v := store.versions["p2"]; len(v) != 1 || v[0].Label != "before-restore" || !strings.Contains(string(v[0].JSON), "from before collab") {
t.Fatalf("versions before replace = %+v", v)
}
if c, _ := h.Content(ctx, "p2"); !strings.Contains(string(c), "restored") {
t.Fatalf("live content = %s", c)
}
@@ -280,3 +310,53 @@ func TestSeedFromJSONAndReplace(t *testing.T) {
t.Fatalf("saved content = %s", c)
}
}
func TestKickAndDrop(t *testing.T) {
ctx := context.Background()
store := newMemStore()
h, _ := newHub(t, store)
peer := &fakePeer{}
if _, err := h.Join(ctx, "p3", "alice", true, peer); err != nil {
t.Fatal(err)
}
h.Kick("p3")
if peer.closeCode() != CloseAccessChanged {
t.Fatalf("kick close code = %d", peer.closeCode())
}
h.Drop("p3")
if peer.closeCode() != CloseGone {
t.Fatalf("drop close code = %d", peer.closeCode())
}
h.mu.Lock()
defer h.mu.Unlock()
if h.rooms["p3"] != nil {
t.Fatal("dropped room still open")
}
}
// A page deleted with its space (no Drop call) is noticed on the next failed
// write, instead of retrying forever.
func TestDeletedPageClosesRoom(t *testing.T) {
ctx := context.Background()
store := newMemStore()
h, pool := newHub(t, store)
peer := &fakePeer{}
s, err := h.Join(ctx, "p4", "alice", true, peer)
if err != nil {
t.Fatal(err)
}
store.mu.Lock()
store.deleted["p4"] = true
store.mu.Unlock()
edit, _ := pool.Replace(ctx, nil, docJSON("lost"))
if err := s.Receive(ctx, syncMessage(syncUpdate, edit)); err != nil {
t.Fatal(err)
}
waitFor(t, "room of a deleted page to close", func() bool {
h.mu.Lock()
defer h.mu.Unlock()
return h.rooms["p4"] == nil && peer.closeCode() == CloseGone
})
}
+38 -14
View File
@@ -23,6 +23,8 @@ type Stored struct {
ContentJSON json.RawMessage
// LastVersion is when the newest page version was taken (zero if none).
LastVersion time.Time
// Unversioned is true when the saved document changed after the newest version.
Unversioned bool
}
// Snapshot is a compacted document and what was derived from it.
@@ -31,6 +33,8 @@ type Snapshot struct {
JSON []byte
Text string
LastEditor string
// Label names a version (AddVersion only).
Label string
// Covers lists flushed update records that State already includes.
Covers []string
}
@@ -62,11 +66,15 @@ func NewPBStore(pb *pocketbase.Client) *PBStore { return &PBStore{pb: pb} }
var b64 = base64.StdEncoding
// pbTime is how PocketBase formats dates.
const pbTime = "2006-01-02 15:04:05.000Z"
func (s *PBStore) Load(ctx context.Context, page string) (Stored, error) {
var out Stored
ydoc, err := pocketbase.List[struct {
State string `json:"state"`
}](ctx, s.pb, "page_ydoc", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Fields: "state"})
State string `json:"state"`
Updated string `json:"updated"`
}](ctx, s.pb, "page_ydoc", pocketbase.ListOptions{PerPage: 1, Filter: fmt.Sprintf("page = '%s'", page), Fields: "state,updated"})
if err != nil {
return out, err
}
@@ -109,7 +117,13 @@ func (s *PBStore) Load(ctx context.Context, page string) (Stored, error) {
return out, err
}
if len(versions.Items) > 0 {
out.LastVersion, _ = time.Parse("2006-01-02 15:04:05.000Z", versions.Items[0].Created)
out.LastVersion, _ = time.Parse(pbTime, versions.Items[0].Created)
}
// A saved document newer than the newest version (or pending updates) still needs one.
out.Unversioned = len(out.Updates) > 0
if len(ydoc.Items) > 0 {
saved, _ := time.Parse(pbTime, ydoc.Items[0].Updated)
out.Unversioned = out.Unversioned || saved.After(out.LastVersion)
}
return out, nil
}
@@ -128,18 +142,10 @@ func (s *PBStore) SaveSnapshot(ctx context.Context, page string, snap Snapshot)
if err != nil {
return err
}
body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State)}
type rec struct {
ID string `json:"id"`
}
if len(existing.Items) > 0 {
_, err = pocketbase.Update[rec](ctx, s.pb, "page_ydoc", existing.Items[0].ID, body)
} else {
_, err = pocketbase.Create[rec](ctx, s.pb, "page_ydoc", body)
}
if err != nil {
return err
}
// The page first: for a deleted page this fails with ErrNotFound.
patch := map[string]any{
"content_json": json.RawMessage(snap.JSON), "content_text": snap.Text, "word_count": len(strings.Fields(snap.Text)),
}
@@ -147,6 +153,15 @@ func (s *PBStore) SaveSnapshot(ctx context.Context, page string, snap Snapshot)
patch["last_editor"] = snap.LastEditor
}
if _, err := pocketbase.Update[rec](ctx, s.pb, "pages", page, patch); err != nil {
return notFound(err)
}
body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State)}
if len(existing.Items) > 0 {
_, err = pocketbase.Update[rec](ctx, s.pb, "page_ydoc", existing.Items[0].ID, body)
} else {
_, err = pocketbase.Create[rec](ctx, s.pb, "page_ydoc", body)
}
if err != nil {
return err
}
for _, id := range snap.Covers {
@@ -158,7 +173,9 @@ func (s *PBStore) SaveSnapshot(ctx context.Context, page string, snap Snapshot)
}
func (s *PBStore) AddVersion(ctx context.Context, page string, snap Snapshot) error {
body := map[string]any{"page": page, "state": b64.EncodeToString(snap.State), "content_json": json.RawMessage(snap.JSON)}
body := map[string]any{
"page": page, "state": b64.EncodeToString(snap.State), "content_json": json.RawMessage(snap.JSON), "label": snap.Label,
}
if snap.LastEditor != "" {
body["author"] = snap.LastEditor
}
@@ -173,7 +190,7 @@ func (s *PBStore) Content(ctx context.Context, page string) (json.RawMessage, er
ContentJSON json.RawMessage `json:"content_json"`
}](ctx, s.pb, "pages", page)
if err != nil {
return nil, err
return nil, notFound(err)
}
return nullIfEmpty(rec.ContentJSON), nil
}
@@ -222,6 +239,13 @@ func (s *PBStore) VersionContent(ctx context.Context, page, id string) (json.Raw
return nullIfEmpty(res.Items[0].ContentJSON), nil
}
func notFound(err error) error {
if pocketbase.IsNotFound(err) {
return ErrNotFound
}
return err
}
func nullIfEmpty(raw json.RawMessage) json.RawMessage {
if len(raw) == 0 || string(raw) == `""` {
return json.RawMessage("null")
+7 -3
View File
@@ -21,7 +21,11 @@ const maxContentBytes = 8 << 20
// Docs is the part of collab.Hub that holds page documents.
type Docs interface {
Content(ctx context.Context, page string) (json.RawMessage, error)
Replace(ctx context.Context, page, user string, doc json.RawMessage) error
Replace(ctx context.Context, page, user string, doc json.RawMessage, label string) error
// Kick reconnects the page's editors, so they pick up changed rights.
Kick(page string)
// Drop forgets a deleted page's live document.
Drop(page string)
Versions(ctx context.Context, page string) ([]collab.Version, error)
VersionContent(ctx context.Context, page, id string) (json.RawMessage, error)
}
@@ -63,7 +67,7 @@ func (s *Service) SavePageContent(ctx context.Context, c access.Caller, id strin
if !isDoc(in.Content) {
return PageContent{}, apperr.InvalidFields(map[string]string{"content": "Content must be a Tiptap document."})
}
if err := s.docs.Replace(ctx, p.ID, c.ID, in.Content); err != nil {
if err := s.docs.Replace(ctx, p.ID, c.ID, in.Content, "before-replace"); err != nil {
return PageContent{}, err
}
return s.GetPageContent(ctx, c, p.ID)
@@ -112,7 +116,7 @@ func (s *Service) RestoreVersion(ctx context.Context, c access.Caller, id, versi
if !isDoc(doc) {
doc = json.RawMessage(`{"type":"doc","content":[]}`)
}
if err := s.docs.Replace(ctx, p.ID, c.ID, doc); err != nil {
if err := s.docs.Replace(ctx, p.ID, c.ID, doc, "before-restore"); err != nil {
return PageContent{}, err
}
return s.GetPageContent(ctx, c, p.ID)
+9 -1
View File
@@ -425,6 +425,9 @@ func (s *Service) TrashPage(ctx context.Context, c access.Caller, id string) err
_, err = pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, map[string]any{
"deleted_at": pbTime(time.Now()), "last_editor": c.ID,
})
if err == nil {
s.docs.Kick(p.ID)
}
return mapPB(err, "page not found")
}
@@ -456,6 +459,7 @@ func (s *Service) RestorePage(ctx context.Context, c access.Caller, id string) (
if _, err := pocketbase.Update[pageRecord](ctx, s.pb, "pages", p.ID, patch); err != nil {
return Page{}, mapPB(err, "page not found")
}
s.docs.Kick(p.ID)
return s.GetPage(ctx, c, p.ID)
}
@@ -492,5 +496,9 @@ func (s *Service) PurgePage(ctx context.Context, c access.Caller, id string) err
if p.DeletedAt == "" {
return apperr.Invalid("move the page to the trash first")
}
return mapPB(s.pb.Delete(ctx, "pages", p.ID), "page not found")
if err := s.pb.Delete(ctx, "pages", p.ID); err != nil {
return mapPB(err, "page not found")
}
s.docs.Drop(p.ID)
return nil
}
+40 -2
View File
@@ -9,9 +9,14 @@ import (
"github.com/coder/websocket"
"docwell/server/internal/access"
"docwell/server/internal/collab"
)
// recheckEvery is how often an open connection's access is checked again, so
// role changes reach editors that stay connected.
var recheckEvery = 30 * time.Second
// CollabHub is the part of collab.Hub the WebSocket endpoint uses.
type CollabHub interface {
Join(ctx context.Context, page, user string, canWrite bool, p collab.Peer) (*collab.Session, error)
@@ -20,7 +25,7 @@ type CollabHub interface {
// Close codes the editor reacts to (4000–4999 are free for applications).
const (
closeUnauthorized = 4401
closeNotFound = 4404
closeNotFound = collab.CloseGone
)
// collabRoute serves /collab?page=<id>: the y-websocket protocol for one page.
@@ -69,7 +74,7 @@ func (a *api) serveCollab(ctx context.Context, conn *websocket.Conn, page string
ctx, cancel = context.WithCancel(ctx)
defer cancel()
p := &wsPeer{out: make(chan []byte, 1024), cancel: cancel}
p := &wsPeer{out: make(chan []byte, 1024), cancel: cancel, conn: conn}
go p.write(ctx, conn)
session, err := a.collab.Join(ctx, page, user.ID, canWrite, p)
if err != nil {
@@ -78,6 +83,7 @@ func (a *api) serveCollab(ctx context.Context, conn *websocket.Conn, page string
return
}
defer session.Leave()
go a.recheckCollab(ctx, p, user.Caller(), page, canWrite)
for {
typ, msg, err := conn.Read(ctx)
if err != nil {
@@ -93,11 +99,43 @@ func (a *api) serveCollab(ctx context.Context, conn *websocket.Conn, page string
}
}
// recheckCollab disconnects the peer once its access to the page changes:
// gone (no longer allowed, or page deleted) or a different write right. The
// editor then reloads the page and reconnects with its new rights.
func (a *api) recheckCollab(ctx context.Context, p *wsPeer, c access.Caller, page string, canWrite bool) {
t := time.NewTicker(recheckEvery)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
now, err := a.dir.CollabAccess(ctx, c, page)
switch {
case ctx.Err() != nil:
return
case err != nil:
p.Close(collab.CloseGone, "page not found")
return
case now != canWrite:
p.Close(collab.CloseAccessChanged, "access changed")
return
}
}
}
// wsPeer queues outgoing messages; a peer that falls 1024 messages behind is
// disconnected and catches up through a fresh sync when it reconnects.
type wsPeer struct {
out chan []byte
cancel context.CancelFunc
conn *websocket.Conn
}
// Close sends a close frame; the read loop then ends and the session leaves.
func (p *wsPeer) Close(code int, reason string) {
go p.conn.Close(websocket.StatusCode(code), reason)
}
func (p *wsPeer) Send(msg []byte) bool {
@@ -11,7 +11,7 @@ import { useApi } from "../api";
const props = defineProps<{ page: Page; canRestore: boolean }>();
const emit = defineEmits<{ close: []; error: [err: unknown] }>();
const api = useApi();
const { t, locale } = useI18n();
const { t, te, locale } = useI18n();
const versions = ref<PageVersion[] | null>(null);
const selected = ref<PageVersion | null>(null);
@@ -54,6 +54,9 @@ async function restore() {
}
}
// Labels are codes set by the server, e.g. "before-restore".
const labelText = (label: string) => (label && te(`page.history.labels.${label}`) ? t(`page.history.labels.${label}`) : label);
// PocketBase dates look like "2026-10-30 21:05:00.000Z".
const when = (s: string) =>
new Date(s.replace(" ", "T")).toLocaleString(locale.value, { dateStyle: "medium", timeStyle: "short" });
@@ -82,7 +85,9 @@ const when = (s: string) =>
@click="select(v)"
>
<span class="block">{{ when(v.created) }}</span>
<span v-if="v.author" class="block text-ui-sm text-ink-muted">{{ v.author }}</span>
<span v-if="v.label || v.author" class="block text-ui-sm text-ink-muted">
{{ [labelText(v.label), v.author].filter(Boolean).join(" · ") }}
</span>
</button>
</li>
</ul>
+5 -1
View File
@@ -208,7 +208,11 @@
"empty": "No versions yet. One is saved every few minutes while people edit.",
"pick": "Pick a version to see it.",
"restore": "Restore this version",
"confirmRestore": "Replace the page with the version from {date}? The current text stays in the history."
"confirmRestore": "Replace the page with the version from {date}? The current text stays in the history.",
"labels": {
"before-restore": "Before a restore",
"before-replace": "Before a replace"
}
},
"notFound": "This page does not exist or you don't have access to it."
},
+5 -1
View File
@@ -208,7 +208,11 @@
"empty": "Brak wersji. Nowa wersja zapisuje się co kilka minut podczas edycji.",
"pick": "Wybierz wersję, aby ją zobaczyć.",
"restore": "Przywróć tę wersję",
"confirmRestore": "Zastąpić stronę wersją z {date}? Obecny tekst zostanie w historii."
"confirmRestore": "Zastąpić stronę wersją z {date}? Obecny tekst zostanie w historii.",
"labels": {
"before-restore": "Przed przywróceniem",
"before-replace": "Przed zastąpieniem"
}
},
"notFound": "Ta strona nie istnieje lub nie masz do niej dostępu."
},
+29
View File
@@ -73,6 +73,35 @@ describe("auth store", () => {
expect(tokens.get()).toBeNull();
});
it("init keeps the token while the server is unreachable", async () => {
const tokens = memoryTokens("saved");
const refresh = vi.fn(async () => {
throw new ApiError(502, "Bad Gateway");
});
const store = useAuthStore();
store.attach(fakeApi({ refresh }), tokens);
await store.init([0, 0]);
expect(refresh).toHaveBeenCalledTimes(3);
expect(store.ready).toBe(true);
expect(store.isSignedIn).toBe(false);
expect(tokens.get()).toBe("saved");
});
it("init retries a network error and signs in once the server answers", async () => {
const tokens = memoryTokens("saved");
const refresh = vi
.fn()
.mockRejectedValueOnce(new TypeError("Failed to fetch"))
.mockResolvedValueOnce({ token: "new", user: ann });
const store = useAuthStore();
store.attach(fakeApi({ refresh }), tokens);
await store.init([0]);
expect(store.isSignedIn).toBe(true);
expect(tokens.get()).toBe("new");
});
it("init without a token does not call the server", async () => {
const refresh = vi.fn();
const store = useAuthStore();
+30 -6
View File
@@ -1,4 +1,4 @@
import type { DocwellClient, Session, SignupRequest, User } from "@docwell/api-client";
import { ApiError, type DocwellClient, type Session, type SignupRequest, type User } from "@docwell/api-client";
import { defineStore } from "pinia";
import { computed, ref, shallowRef } from "vue";
@@ -7,6 +7,11 @@ interface TokenStore {
set(token: string | null): void;
}
/** Waits between start-up refresh attempts while the server is unreachable (~7.5 s in all). */
export const refreshRetryDelays = [500, 1000, 2000, 4000];
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export const useAuthStore = defineStore("auth", () => {
const user = ref<User | null>(null);
const ready = ref(false);
@@ -36,13 +41,32 @@ export const useAuthStore = defineStore("auth", () => {
user.value = null;
}
/** Restores the saved session (refreshing its token) on app start. */
async function init() {
/**
* Restores the saved session (refreshing its token) on app start. Only the
* server rejecting the token signs the user out; while the server is
* unreachable (restarting, offline) it retries, then keeps the token so the
* next load can try again.
*/
async function init(delays = refreshRetryDelays) {
if (ready.value) return;
try {
if (tokens?.get()) setSession(await client().auth.refresh());
} catch {
clear();
if (!tokens?.get()) return;
for (let attempt = 0; ; attempt++) {
try {
setSession(await client().auth.refresh());
return;
} catch (e) {
if (e instanceof ApiError && e.status >= 400 && e.status < 500) {
clear();
return;
}
if (attempt >= delays.length) {
user.value = null;
return;
}
await sleep(delays[attempt]!);
}
}
} finally {
ready.value = true;
}
+12 -2
View File
@@ -49,21 +49,31 @@ function openDoc(id: string) {
closeDoc();
const p = new CollabProvider({ url: collabUrl(), page: id, token });
const refresh = () => {
if (provider.value !== p) return;
if (p.status === "changed") {
// Rights or the page changed: reload it and reopen with a fresh document.
closeDoc();
load(id);
return;
}
collabStatus.value = p.status;
synced.value = p.synced;
others.value = [...p.awareness.getStates()]
.filter(([client, s]) => client !== p.doc.clientID && s.user)
.map(([, s]) => s.user as { name: string; color: string });
};
provider.value = p;
p.onChange(refresh);
p.awareness.on("change", refresh);
refresh();
provider.value = p;
}
function closeDoc() {
provider.value?.destroy();
// Detach first: destroying the provider changes its awareness, which would
// otherwise call refresh again.
const p = provider.value;
provider.value = null;
p?.destroy();
}
const editable = computed(() => !!page.value && !page.value.inTrash && spaceAtLeast(page.value.role, "editor"));