oficina / docs Public

Docs native: straight in with one Oficina ID, Use another, signed-out 403 re-mint

Docs moves to the shared kit's straight-in version (rastrillo/native
1e36aac; Home spec §9 as amended in 2e50b92), as Sheets did in 03d52db:
straight-in suspension bound to the sign-in route; Use another Oficina
ID in the Teams sheet and the Mac app menu, only while signed in and
refused with an open document or unsent changes; the replace
confirmation on the signed-in screen only. A native session past 7 days
now gets 403 "signed out" (pinned by native_contract_test.go), which the
app re-mints instead of holding the write as access lost.

Discussion oficina/docs #130. Reviewed by Claude Fable 5.2: APPROVE (seven
LOW follow-ups tracked there; the server must deploy before the app
ships). Hub CI passed at 2e70647.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 7de2d40c1c77a8b43544a4b47c7806411eafd65f parent 0250ef1
18 files changed, +676 −40
  • internal/docs/auth.go +1 −1
  • internal/docs/identity.go +28 −4
  • internal/docs/native_contract_test.go +102 −0
  • native/BUILDING.md +18 −0
  • native/apple/Package.resolved +1 −1
  • native/apple/Package.swift +3 −2
  • native/apple/Sources/DocsApp/DocsAccountWindow.swift +66 −12
  • native/apple/Sources/DocsApp/DocsWindowCommands.swift +9 −2
  • native/apple/Sources/DocsKit/DocsAccountActions.swift +6 −0
  • native/apple/Sources/DocsKit/DocsOficinaID.swift +58 −5
  • native/apple/Sources/DocsKit/DocsOficinaViews.swift +18 −6
  • native/apple/Sources/DocsKit/DocsWorkspace.swift +7 −3
  • native/apple/Sources/DocsKit/Resources/Colophon.json +1 −1
  • native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift +205 −0
  • native/apple/Tests/DocsWindowTests/SignedInLaunchTests.swift +150 −0
  • native/ios/project.yml +1 −1
  • native/macos/project.yml +1 −1
  • native/notices/native/provenance.json +1 −1

CI passed — run details

diff --git a/internal/docs/auth.go b/internal/docs/auth.go
index 259a28a..682cfb7 100644
--- a/internal/docs/auth.go
+++ b/internal/docs/auth.go
@@ -330,7 +330,7 @@ func requireAdmission(list allowlist, signinPath string) func(http.Handler) http
// to match an allowed address. It must not take the legacy fallback.
if s, ok := sessions.Current(r); ok && connect.IsHomeDerived(s.Method) {
if _, resolved := currentIdentity(r); !resolved {
- refuseIdentity(w, r, signinPath)
+ refuseIdentity(w, r, signinPath, false)
return
}
}
diff --git a/internal/docs/identity.go b/internal/docs/identity.go
index 956b245..c66f164 100644
--- a/internal/docs/identity.go
+++ b/internal/docs/identity.go
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"errors"
+ "fmt"
"net/http"
"time"
@@ -24,8 +25,22 @@ const homeAssertionMethod = connect.HomeMethod
var (
errIdentityRefused = errors.New("docs: identity refused")
errIdentityStorage = errors.New("docs: identity storage unavailable")
+ // errSessionEnded is a native or native-web session past its seven days
+ // (connect.Expired): refused like any identity, but ended rather than
+ // refused, so a non-GET says so in the session guard's own words.
+ errSessionEnded = fmt.Errorf("%w: session ended", errIdentityRefused)
)
+// sessionEndedBody is what every session guard answers a non-GET whose
+// session has ended: byte for byte rastrillo sessions.Require's refusal of
+// a missing, unknown or revoked session ("signed out", and http.Error adds
+// the newline). A wire contract, not copy: the native apps' Oficina ID
+// transport (native/apple/Sources/DocsKit/DocsOficinaID.swift,
+// DocsSessionWatch.signedOut) reads a 403 with exactly this body as an
+// ended session and re-mints it, where any other 403 is a refusal of the
+// request. native_contract_test.go pins it on every guard.
+const sessionEndedBody = "signed out"
+
// requestIdentity keeps the verified session separate from the local person
// and address that own documents and hold grants.
type requestIdentity struct {
@@ -85,7 +100,7 @@ func (v identityResolver) resolve(r *http.Request) (requestIdentity, error) {
// recently used (connect.Expired); Docs resolves sessions itself,
// so it refuses what connect's ResolveSession would.
if connect.Expired(connect.Session{Subject: session.Subject, Method: session.Method, AuthTime: session.AuthTime, At: session.At}, time.Now()) {
- return requestIdentity{}, errIdentityRefused
+ return requestIdentity{}, errSessionEnded
}
person, err := v.homePerson(r.Context(), session.Subject)
if err != nil {
@@ -166,7 +181,7 @@ func (v identityResolver) middleware(signinPath string) func(http.Handler) http.
if errors.Is(err, errIdentityStorage) {
http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusServiceUnavailable)
} else {
- refuseIdentity(w, r, signinPath)
+ refuseIdentity(w, r, signinPath, errors.Is(err, errSessionEnded))
}
return
}
@@ -175,12 +190,21 @@ func (v identityResolver) middleware(signinPath string) func(http.Handler) http.
}
}
-func refuseIdentity(w http.ResponseWriter, r *http.Request, signinPath string) {
+// refuseIdentity sends a page request to sign-in and answers anything else
+// 403. A session that has ended says so as the session guard does
+// (sessionEndedBody), so a native app re-mints it rather than reading a
+// refused request: its outbox would otherwise hold the write as access
+// lost. Any other refusal keeps the generic line.
+func refuseIdentity(w http.ResponseWriter, r *http.Request, signinPath string, ended bool) {
if r.Method == http.MethodGet || r.Method == http.MethodHead {
http.Redirect(w, r, signinPath, http.StatusSeeOther)
return
}
- http.Error(w, rastrillo.T(r, "docs.error.generic"), http.StatusForbidden)
+ body := rastrillo.T(r, "docs.error.generic")
+ if ended {
+ body = sessionEndedBody
+ }
+ http.Error(w, body, http.StatusForbidden)
}
// requestActor supports standalone routes without the suite middleware too.
diff --git a/internal/docs/native_contract_test.go b/internal/docs/native_contract_test.go
new file mode 100644
index 0000000..8d03286
--- /dev/null
+++ b/internal/docs/native_contract_test.go
@@ -0,0 +1,102 @@
+package docs
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/home/connect"
+)
+
+// A native contract, not copy: the native apps' Oficina ID transport
+// (native/apple/Sources/DocsKit/DocsOficinaID.swift,
+// DocsSessionWatch.signedOut) reads a 403 whose body is exactly
+// "signed out\n" as an ended session and re-mints it; any other 403 is a
+// refusal of the request, which the outbox holds as access lost. Every
+// guard that refuses a non-GET request for want of a live session must
+// keep these bytes: rastrillo sessions.Require's own refusal (no session,
+// an unknown or revoked one), and Docs' identity guard for a native
+// session past its seven days (refuseIdentity, sessionEndedBody). Changing
+// either strands a native window whose first request after the session
+// ends is a write.
+const nativeSignedOut = "signed out\n"
+
+func assertSignedOut(t *testing.T, where string, rec *httptest.ResponseRecorder) {
+ t.Helper()
+ if rec.Code != http.StatusForbidden || rec.Body.String() != nativeSignedOut {
+ t.Fatalf("%s = %d %q, want 403 %q (the native transport's re-mint signal)", where, rec.Code, rec.Body.String(), nativeSignedOut)
+ }
+}
+
+// nativeWrite is the native app's request as NativeHTTP sends it: JSON
+// wanted, the instance's own Origin, and the session cookie if any.
+func nativeWrite(f *routerHomeFixture, method, path string, cookie *http.Cookie) *httptest.ResponseRecorder {
+ r := httptest.NewRequest(method, bridgeOrigin+path, strings.NewReader(`{"title":"x"}`))
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("Accept", "application/json")
+ r.Header.Set("Origin", bridgeOrigin)
+ if cookie != nil {
+ r.AddCookie(cookie)
+ }
+ return f.browser().serve(r)
+}
+
+func TestNativeContractNoSessionSaysSignedOut(t *testing.T) {
+ f, _ := homeNativeFixture(t)
+ _, answer := f.nativeExchange(t, "pr_alice", nil)
+ assertSignedOut(t, "sessions.Require, no cookie", nativeWrite(f, "POST", "/documents", nil))
+ assertSignedOut(t, "sessions.Require, unknown session",
+ nativeWrite(f, "POST", "/documents", &http.Cookie{Name: answer.Name, Value: "not-a-session"}))
+}
+
+func TestNativeContractEndedNativeSessionSaysSignedOut(t *testing.T) {
+ f, _ := homeNativeFixture(t)
+ _, answer := f.nativeExchange(t, "pr_alice", nil)
+ cookie := &http.Cookie{Name: answer.Name, Value: answer.Value}
+ if rec := nativeWrite(f, "POST", "/documents", cookie); rec.Code != http.StatusCreated {
+ t.Fatalf("a fresh native session could not write: %d %q", rec.Code, rec.Body.String())
+ }
+ ageSession(t, f, answer.Value, connect.NativeLifetime+time.Hour)
+ assertSignedOut(t, "refuseIdentity, native session past seven days", nativeWrite(f, "POST", "/documents", cookie))
+ assertSignedOut(t, "refuseIdentity, native session past seven days, update log",
+ nativeWrite(f, "POST", "/d/anything/updates", cookie))
+ // A page request goes to sign-in, which the native client reads as an
+ // ended session too.
+ if rec := nativeWrite(f, "GET", "/", cookie); rec.Code != http.StatusSeeOther {
+ t.Fatalf("GET with an ended native session = %d, want 303 to sign-in", rec.Code)
+ }
+}
+
+func TestNativeContractTeamEndedNativeSessionSaysSignedOut(t *testing.T) {
+ f := newTeamRouterFixture(t)
+ _, answer := f.nativeExchange(t, teamSubject('b'), map[string]string{"choice": "new"})
+ if answer.Value == "" {
+ t.Fatal("the team native exchange minted nothing")
+ }
+ cookie := &http.Cookie{Name: answer.Name, Value: answer.Value}
+ ageSession(t, f.routerHomeFixture, answer.Value, connect.NativeLifetime+time.Hour)
+ assertSignedOut(t, "team mode, native session past seven days", nativeWrite(f.routerHomeFixture, "POST", "/documents", cookie))
+ assertSignedOut(t, "team mode, unknown session",
+ nativeWrite(f.routerHomeFixture, "POST", "/documents", &http.Cookie{Name: answer.Name, Value: "not-a-session"}))
+}
+
+// Only an ended session says so: a refused identity or request keeps the
+// generic line, or the native app would re-mint a session that is fine
+// and report a refusal as signed out.
+func TestNativeContractOtherRefusalsDoNotSaySignedOut(t *testing.T) {
+ r := httptest.NewRequest("POST", bridgeOrigin+"/documents", nil)
+ r.Header.Set("Accept", "application/json")
+ rec := httptest.NewRecorder()
+ refuseIdentity(rec, r, "/signin", false)
+ if rec.Code != http.StatusForbidden || rec.Body.String() == nativeSignedOut {
+ t.Fatalf("refuseIdentity, refused identity = %d %q, want a 403 that is not the ended-session body", rec.Code, rec.Body.String())
+ }
+ rec = httptest.NewRecorder()
+ refuseIdentity(rec, r, "/signin", true)
+ assertSignedOut(t, "refuseIdentity, ended", rec)
+ if sessionEndedBody+"\n" != nativeSignedOut {
+ t.Fatalf("sessionEndedBody = %q, the native contract is %q", sessionEndedBody, nativeSignedOut)
+ }
+}
diff --git a/native/BUILDING.md b/native/BUILDING.md
index 5e85ccb..b7faf88 100644
--- a/native/BUILDING.md
+++ b/native/BUILDING.md
@@ -105,6 +105,24 @@ associated domain) and both keychain groups, prints counts (never an identity
or a session) and exits 0 only if all of them work. An ad hoc build, or the
unsigned test runner (`OficinaIDAdoptionTests`), fails every line.
+With one Oficina ID on the device Docs goes straight in, with no screen
+(Paul, 2026-11-19; spec §9 "Straight in", rule 0); several ask which. While
+"Other ways to sign in…" is the route, nothing goes straight in: the home
+window suspends it at launch and on every route change (`routeChanged`, from
+`.onChange(of: route)`), and resumes it when the route is Oficina ID again. A
+signed-in session is never disturbed by either. The account menu (the Teams
+sheet, and Docs ▸ in the Mac menu bar) offers "Use another Oficina ID" only
+while signed in; the kit confirms (`oficinaReplaceConfirmation`, on the
+signed-in screen only), and Docs refuses, and says why, while a document
+window of the identity is open or its changes are unsent.
+
+Docs' session guards answer a write whose session has ended with 403
+`signed out` (rastrillo's `sessions.Require`, and the identity guard for a
+native session past its seven days). `DocsSessionWatch` reads exactly those
+bytes as an ended session, re-mints it and surfaces a 401; every other 403 is
+a refusal of the request. `internal/docs/native_contract_test.go` pins the
+bytes on the server.
+
An Oficina ID team's offline store key is filed under one fixed origin, not the
team's, so a team whose address changes (a label moved, a rename, self-hosting
by DNS) keeps its store and unsent outbox. Docs refreshes the team list at
diff --git a/native/apple/Package.resolved b/native/apple/Package.resolved
index 25ad9fc..e407732 100644
--- a/native/apple/Package.resolved
+++ b/native/apple/Package.resolved
@@ -6,7 +6,7 @@
"kind" : "remoteSourceControl",
"location" : "https://amadan.net/rastrillo/native",
"state" : {
- "revision" : "f1c7a14db2ddb8960afabc8268cd92c490543397"
+ "revision" : "1e36aac95ed252848722926efc8ba8f9dc803216"
}
},
{
diff --git a/native/apple/Package.swift b/native/apple/Package.swift
index 307a172..ba6dd9f 100644
--- a/native/apple/Package.swift
+++ b/native/apple/Package.swift
@@ -3,7 +3,7 @@ import PackageDescription
import Foundation
let sharedNative: Package.Dependency = ProcessInfo.processInfo.environment["OFICINA_NATIVE_PACKAGE_PATH"].map { .package(name: "native", path: $0) }
- ?? .package(url: "https://amadan.net/rastrillo/native", revision: "f1c7a14db2ddb8960afabc8268cd92c490543397")
+ ?? .package(url: "https://amadan.net/rastrillo/native", revision: "1e36aac95ed252848722926efc8ba8f9dc803216")
let package = Package(name: "DocsNative", defaultLocalization: "en", platforms: [.macOS(.v26), .iOS(.v26)],
products: [.library(name: "DocsKit", targets: ["DocsKit"]), .executable(name: "DocsMac", targets: ["DocsMac"])],
@@ -13,7 +13,8 @@ let package = Package(name: "DocsNative", defaultLocalization: "en", platforms:
.target(name: "DocsKit", dependencies: ["DocsCRDT", .product(name: "RastrilloApple", package: "native")], resources: [.process("Resources"), .copy("Fonts")]),
.executableTarget(name: "DocsMac", dependencies: [.product(name: "RastrilloMacUpdates", package: "native", condition: .when(platforms: [.macOS])), "DocsKit", .product(name: "RastrilloApple", package: "native")], path: "Sources/DocsApp"),
.testTarget(name: "DocsKitTests", dependencies: ["DocsKit", .product(name: "RastrilloTestSupport", package: "native")]),
- .testTarget(name: "DocsWindowTests", dependencies: ["DocsMac", .product(name: "RastrilloApple", package: "native")]),
+ .testTarget(name: "DocsWindowTests", dependencies: ["DocsMac", "DocsKit", .product(name: "RastrilloApple", package: "native"),
+ .product(name: "RastrilloTestSupport", package: "native")]),
// The screenshot gate's Mac half; native/scripts/snapshots.sh runs it,
// plain `swift test` skips it. ios/project.yml builds the same file
// as DocsPhoneSnapshots for the iPhone half.
diff --git a/native/apple/Sources/DocsApp/DocsAccountWindow.swift b/native/apple/Sources/DocsApp/DocsAccountWindow.swift
index abb08b6..913e818 100644
--- a/native/apple/Sources/DocsApp/DocsAccountWindow.swift
+++ b/native/apple/Sources/DocsApp/DocsAccountWindow.swift
@@ -5,12 +5,19 @@ import SwiftUI
/// Each window owns its navigation and model lifetime. Switching an account in
/// one window must never discard another window's unconfirmed edits.
///
-/// Sign-in is Oficina ID first (spec 2026-11-14-oficina-id-native, slice A):
-/// the kit's onboarding until its model is signed in to a team, then that
-/// team's workspace. "Other ways to sign in…" is the server address and
-/// browser approval that came before, kept for self-hosted servers and local
+/// Sign-in is Oficina ID first (spec 2026-11-14-oficina-id-native, slice A,
+/// and Paul's straight-in ruling of 2026-11-19): with one Oficina ID on the
+/// device Docs opens its team with no screen at all; otherwise the kit's
+/// onboarding until its model is signed in to a team, then that team's
+/// workspace. "Other ways to sign in…" is the server address and browser
+/// approval that came before, kept for self-hosted servers and local
/// accounts; someone already signed in that way keeps those accounts until an
-/// Oficina ID replaces them (`DocsSignInRoute`).
+/// Oficina ID replaces them (`DocsSignInRoute`), and nothing goes straight in
+/// while they do.
+///
+/// The body only reads: every change (start, route, suspension, the
+/// replace guard) happens in `.task`, `.onChange` or a button, never while
+/// building a view (84d1008, WorkspaceInitTests, SignedInLaunchTests).
struct DocsAccountWindow: View {
@ObservedObject private var oficina: DocsOficinaSession
@ObservedObject private var model: OficinaIDModel
@@ -50,22 +57,38 @@ struct DocsAccountWindow: View {
case .oficinaID:
// The mounted team stays while Oficina ID can't re-mint it (§11), with
// the line saying so over it, rather than unmounting an open editor.
- if let state = oficina.mounted { oficinaWorkspace(state).safeAreaInset(edge: .top, spacing: 0) { oficinaBanner } }
- else { OficinaOnboardingView(model: model, otherWays: { storedRoute = DocsSignInRoute.server.rawValue }) }
+ if let state = oficina.mounted {
+ oficinaWorkspace(state)
+ .safeAreaInset(edge: .top, spacing: 0) { oficinaBanner }
+ // The account menu's "Use another Oficina ID" asks here; the
+ // onboarding carries its own for every other step.
+ .oficinaReplaceConfirmation(model)
+ } else {
+ OficinaOnboardingView(model: model, otherWays: { storedRoute = DocsSignInRoute.server.rawValue })
+ }
case .server:
if let client = connection.client { serverWorkspace(client) }
else { DocsOtherWaysView(connection: connection) { storedRoute = DocsSignInRoute.oficinaID.rawValue } }
}
}
.onOpenURL(perform: connection.handleOpenURL)
- .task { await oficina.start() }
+ .task { await oficina.start(serverRoute: route == .server) }
// A sign-in with Oficina ID replaces the other ways for good (Appendix C).
- // Only one made here: an identity restored at launch (another app's, or
- // last run's) leaves the route someone chose alone.
+ // Only one made here: going straight in at launch (another app's
+ // identity, or last run's) leaves the route someone chose alone.
.onChange(of: oficina.signIns) { _, _ in storedRoute = DocsSignInRoute.oficinaID.rawValue }
- // "Use another" signs the identity out on every app: Docs' guards first.
+ // Straight in is suspended exactly while Docs' own sign-in is the route,
+ // however the route changes: chosen, or flipped by the last server
+ // account signing out (rule 0). Signed in, the session is undisturbed.
+ .onChange(of: route) { _, value in Task { await oficina.routeChanged(to: value) } }
+ // "Use another" signs the identity out on every app, so Docs' guards are
+ // checked again while the kit asks: never over an outage (no dialog to
+ // ask with on the mounted workspace), never with a document window of
+ // the identity open, never with changes unsent.
.onChange(of: model.confirmingReplace) { _, confirming in
guard confirming, let identity = model.identity?.id else { return }
+ if oficina.mounted != nil, !signedIn { model.cancelReplace(); return }
+ if openDocuments(of: identity) { model.cancelReplace(); leaveRefusal = .openDocuments; return }
Task {
if let block = await DocsLeaveBlock.check(identity: identity, openDocuments: openDocuments(of: identity)) {
model.cancelReplace(); leaveRefusal = block
@@ -86,6 +109,15 @@ struct DocsAccountWindow: View {
if requested && currentClient == nil { windows.signOutRequested = false }
}
.focusedSceneValue(\.docsWindowAccount, currentAccount)
+ // An identity gone (signed out here or in another app, or replaced by
+ // "Use another") takes its closed windows' recents and transports with
+ // it: their sessions are gone.
+ .onChange(of: model.identity?.id) { old, new in
+ guard let old, old != new else { return }
+ windows.entries.removeAll { DocsOficinaSession.account($0.account, belongsTo: old) && !$0.isOpen }
+ let open = Set(windows.entries.filter(\.isOpen).map(\.account))
+ windows.transports = windows.transports.filter { !DocsOficinaSession.account($0.key, belongsTo: old) || open.contains($0.key) }
+ }
.onChange(of: currentAccount, initial: true) { _, value in windows.activeAccount = value }
.onChange(of: settingsAccount, initial: true) { _, value in windows.settingsAccount = value }
.onChange(of: route == .oficinaID ? oficina.mounted?.identity.id : nil, initial: true) { _, value in windows.settingsIdentity = value }
@@ -121,6 +153,7 @@ struct DocsAccountWindow: View {
openWindow(id: "document", value: id)
}, canSignOut: canLeave, createRequested: $windows.createRequested, accountsRequested: $windows.accountsRequested,
signOutRequested: $windows.signOutRequested, accountsLabel: teamsLabel, signOutLabel: OficinaIDText.text("signOut", state.identity.label),
+ useAnother: signedIn ? { useAnother(state) } : nil,
openDocument: { document, title in
guard currentAccount == account else { return }
let id = windows.reserve(account: account, document: document, title: title, client: client)
@@ -145,6 +178,23 @@ struct DocsAccountWindow: View {
private var teamsLabel: String { DocsOficinaSession.teamsTitle }
+ /// Whether the model holds a live team session: "Use another Oficina ID"
+ /// is offered only then, as over an outage there is no dialog to ask with.
+ private var signedIn: Bool {
+ if case .signedIn = model.step { return true }
+ return false
+ }
+
+ /// "Use another Oficina ID" from the account menu. Slice A replaces the
+ /// identity, so the kit asks first (`oficinaReplaceConfirmation`) and the
+ /// sign-out guard applies: refused, and said, with a document window of
+ /// the identity open; unsent changes are checked while the kit asks.
+ private func useAnother(_ state: OficinaSignedIn) {
+ let identity = state.identity.id
+ if openDocuments(of: identity) { leaveRefusal = .openDocuments; return }
+ oficina.useAnother(identity: identity, canLeave: true)
+ }
+
@ViewBuilder private var passkeyNudge: some View {
if model.offerPasskey { OficinaPasskeyNudge(model: model).padding(12) }
}
@@ -181,8 +231,12 @@ struct DocsAccountWindow: View {
await DocsLeaveBlock.check(identity: state.identity.id, openDocuments: openDocuments(of: state.identity.id))
}, refresh: { await oficina.pickerOpened() }, otherWays: {
pickingTeam = false
+ model.suspendStraightIn()
storedRoute = DocsSignInRoute.server.rawValue
- }, signOut: {
+ }, useAnother: signedIn ? {
+ pickingTeam = false
+ useAnother(state)
+ } : nil, signOut: {
pickingTeam = false
signOutOficinaID(state)
}, done: { pickingTeam = false })
diff --git a/native/apple/Sources/DocsApp/DocsWindowCommands.swift b/native/apple/Sources/DocsApp/DocsWindowCommands.swift
index 2a78ddb..70a1197 100644
--- a/native/apple/Sources/DocsApp/DocsWindowCommands.swift
+++ b/native/apple/Sources/DocsApp/DocsWindowCommands.swift
@@ -1,4 +1,5 @@
#if os(macOS)
+import RastrilloApple
import SwiftUI
import DocsKit
@@ -14,11 +15,17 @@ struct DocsWindowCommands: Commands {
Button(DocsColophonView.title) { openWindow(id: "colophon") }
}
CommandGroup(after: .appSettings) {
- Button(docsMacString("Accounts")) {
+ Button(accountActions?.accountsLabel ?? docsMacString("Accounts")) {
if let action = accountActions?.accounts { action() }
else { windows.accountsRequested = true; openWindow(id: "home") }
}.disabled(accountActions?.canManage == false)
- Button(docsMacString("Sign out")) { accountActions?.signOut() }
+ // Only for an Oficina ID, only while signed in, and refused with a
+ // document window of the identity open (the home window re-checks).
+ if let useAnother = accountActions?.useAnother {
+ Button(OficinaIDText.text("continue.another")) { useAnother() }
+ .disabled(accountActions?.canSignOut != true)
+ }
+ Button(accountActions?.signOutLabel ?? docsMacString("Sign out")) { accountActions?.signOut() }
.disabled(accountActions?.canSignOut != true)
Divider()
}
diff --git a/native/apple/Sources/DocsKit/DocsAccountActions.swift b/native/apple/Sources/DocsKit/DocsAccountActions.swift
index 8bca77a..202605e 100644
--- a/native/apple/Sources/DocsKit/DocsAccountActions.swift
+++ b/native/apple/Sources/DocsKit/DocsAccountActions.swift
@@ -5,6 +5,12 @@ public struct DocsAccountActions {
public let signOut: () -> Void
public let canManage: Bool
public let canSignOut: Bool
+ /// "Use another Oficina ID", for an Oficina ID only (Paul, 2026-11-19).
+ public var useAnother: (() -> Void)? = nil
+ /// The menu's words for an Oficina ID ("Teams", "Sign out of <label>");
+ /// nil keeps "Accounts" and "Sign out".
+ public var accountsLabel: String? = nil
+ public var signOutLabel: String? = nil
}
extension FocusedValues { @Entry public var docsAccountActions: DocsAccountActions? }
#endif
diff --git a/native/apple/Sources/DocsKit/DocsOficinaID.swift b/native/apple/Sources/DocsKit/DocsOficinaID.swift
index 58fff20..bb40faf 100644
--- a/native/apple/Sources/DocsKit/DocsOficinaID.swift
+++ b/native/apple/Sources/DocsKit/DocsOficinaID.swift
@@ -16,7 +16,8 @@ public enum DocsSignInRoute: String, Sendable {
/// The route to show. Nothing chosen yet means Oficina ID, except for
/// someone already signed in the old way: their per-app sessions keep
/// working until an Oficina ID replaces them (spec Appendix C). An
- /// Oficina ID sign-in chooses `.oficinaID` for good.
+ /// Oficina ID sign-in chooses `.oficinaID` for good. On `.server` the
+ /// app suspends the kit's straight in (spec §9, rule 0).
public static func resolve(stored: String, hasServerAccounts: Bool) -> DocsSignInRoute {
if let chosen = DocsSignInRoute(rawValue: stored) { return chosen }
return hasServerAccounts ? .server : .oficinaID
@@ -30,6 +31,12 @@ public enum DocsSignInRoute: String, Sendable {
/// is re-minted after 24 hours and on a 401, and the workspace, its offline
/// store and its outbox must carry on through that. So the transport is a
/// supplier that reads the latest session for its account on every request.
+///
+/// Nothing here is read-then-written from a view's body or init (Docs
+/// 0.1.7/0.1.8 hung at launch that way, 84d1008): `mounted`, `sessions` and
+/// `signIns` change only from the model's step publisher, and `start`,
+/// `routeChanged` and `useAnother` run from a `.task`, an `.onChange` or a
+/// button.
@MainActor public final class DocsOficinaSession: ObservableObject {
public let model: OficinaIDModel
private var sessions: [String: (session: NativeSession, client: NativeHTTP)] = [:]
@@ -51,8 +58,9 @@ public enum DocsSignInRoute: String, Sendable {
@Published public private(set) var mounted: OficinaSignedIn?
/// Counts sign-ins a person made here: an identity chosen, a code or
- /// passkey, a team picked, a retry. Restoring the last team at launch is
- /// not one, so a restored identity never changes Docs' sign-in route.
+ /// passkey, a team picked, a retry. Going straight in at launch (the
+ /// last team, or the one Oficina ID on the device) is not one, so it
+ /// never changes Docs' sign-in route.
@Published public private(set) var signIns = 0
/// "Teams": the workspace's button for Docs' team picker.
@@ -84,14 +92,43 @@ public enum DocsSignInRoute: String, Sendable {
}
/// Reads the store once per launch, however many windows ask, then
- /// refreshes the team list (spec §9: at launch).
- public func start() async {
+ /// refreshes the team list (spec §9: at launch). With one Oficina ID on
+ /// the device the kit goes straight in (Paul, 2026-11-19). `serverRoute`
+ /// is Docs' own sign-in being the route: nothing goes straight in then
+ /// (rule 0).
+ public func start(serverRoute: Bool = false) async {
guard !started else { return }
started = true
+ if serverRoute { model.suspendStraightIn() }
await model.start()
await model.refreshTeams()
}
+ /// The route changed, by the person or by itself (the last server
+ /// account signed out, say): straight in is suspended exactly while
+ /// Docs' own sign-in is the route, and resumes when it stops being
+ /// (spec §9, rule 0). Signed in, neither disturbs the session. Call it
+ /// from `.onChange(of: route)`, never from a body.
+ public func routeChanged(to route: DocsSignInRoute) async {
+ switch route {
+ case .server: model.suspendStraightIn()
+ case .oficinaID: await model.resumeStraightIn()
+ }
+ }
+
+ /// "Use another Oficina ID" from the account menu: only while signed in
+ /// (over an outage the team stays mounted, but there is no dialog to
+ /// ask with), and only when `canLeave` (no document window of the
+ /// identity open). The kit then asks (`oficinaReplaceConfirmation`), and
+ /// the window re-checks Docs' guards while it does. Returns whether it
+ /// asked.
+ @discardableResult
+ public func useAnother(identity: String, canLeave: Bool) -> Bool {
+ guard case .signedIn(let state) = model.step, state.identity.id == identity, canLeave else { return false }
+ model.useAnother()
+ return true
+ }
+
/// The team picker opened: refresh if the list is five minutes old.
public func pickerOpened() async { await model.refreshTeams() }
@@ -242,6 +279,15 @@ public enum DocsLeaveBlock: Equatable, Sendable {
/// or the 303 to sign-in that `NativeClientError` also reads as an ended
/// session; and when it refuses a request, a 403. Everything else passes
/// through untouched.
+///
+/// Docs' session guards answer a non-GET request whose session has ended
+/// (none, unknown, revoked, or a native session past its seven days) with
+/// 403 "signed out" (rastrillo sessions.Require, and Docs' identity guard:
+/// internal/docs/identity.go, sessionEndedBody), not 401. Read as a refused
+/// request, a window open past the session's seven days whose first request
+/// is a write would never re-mint, and its outbox would hold the change as
+/// access lost. That one 403 is an ended session, re-minted and surfaced as
+/// the 401 it means; internal/docs/native_contract_test.go pins the bytes.
struct DocsSessionWatch: NativeTransport {
let inner: NativeTransport
let rejected: @Sendable () -> Void
@@ -251,8 +297,15 @@ struct DocsSessionWatch: NativeTransport {
var origin: URL { inner.origin }
+ /// The session guards' refusal, byte for byte (`http.Error` adds the newline).
+ static let signedOut = Data("signed out\n".utf8)
+
func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse {
let reply = try await inner.responseDetails(path, method: method, body: body, contentType: contentType, maxBytes: maxBytes)
+ if reply.status == 403, reply.data == Self.signedOut {
+ rejected()
+ return NativeResponse(data: reply.data, status: 401, headers: reply.headers)
+ }
if reply.status == 401 || reply.status == 303 { rejected() }
if reply.status == 403 { refused() }
return reply
diff --git a/native/apple/Sources/DocsKit/DocsOficinaViews.swift b/native/apple/Sources/DocsKit/DocsOficinaViews.swift
index 65daa9d..61140aa 100644
--- a/native/apple/Sources/DocsKit/DocsOficinaViews.swift
+++ b/native/apple/Sources/DocsKit/DocsOficinaViews.swift
@@ -1,9 +1,11 @@
import RastrilloApple
import SwiftUI
-/// Docs' team picker for an Oficina ID (spec §9): the kit's team list for
-/// the identity, from its team cache, filtered to teams that have Docs. The
-/// several-identities account menu is slice A2; this is one identity's teams.
+/// Docs' account menu for an Oficina ID (spec §9): who is signed in, the
+/// kit's team list for the identity from its team cache, filtered to teams
+/// that have Docs, "Use another Oficina ID" (Paul, 2026-11-19), "Other ways
+/// to sign in…" and "Sign out of <label>". The several-identities menu is
+/// slice A2; this is one identity's teams.
@MainActor public struct DocsTeamPicker: View {
@ObservedObject private var model: OficinaIDModel
private let current: OficinaSignedIn
@@ -12,19 +14,23 @@ import SwiftUI
@State private var block: DocsLeaveBlock?
@State private var checked = false
private let otherWays: () -> Void
+ private let useAnother: (() -> Void)?
private let signOut: () -> Void
private let done: () -> Void
/// `leaveCheck` says why switching team or signing out would strand
/// something (open document windows, changes not yet sent), and the
/// picker shows that line by the controls it disables. `refresh` fetches
- /// the team list again if it is five minutes old (spec §9).
+ /// the team list again if it is five minutes old (spec §9). `useAnother`
+ /// is "Use another Oficina ID", nil while it can't be asked (over an
+ /// outage); it is disabled by the same guard as signing out.
public init(model: OficinaIDModel, current: OficinaSignedIn,
leaveCheck: @escaping @MainActor () async -> DocsLeaveBlock? = { nil },
refresh: @escaping @MainActor () async -> Void = {},
- otherWays: @escaping () -> Void, signOut: @escaping () -> Void, done: @escaping () -> Void) {
+ otherWays: @escaping () -> Void, useAnother: (() -> Void)? = nil,
+ signOut: @escaping () -> Void, done: @escaping () -> Void) {
self.model = model; self.current = current; self.leaveCheck = leaveCheck; self.refresh = refresh
- self.otherWays = otherWays; self.signOut = signOut; self.done = done
+ self.otherWays = otherWays; self.useAnother = useAnother; self.signOut = signOut; self.done = done
}
private var canLeave: Bool { checked && block == nil }
@@ -64,6 +70,12 @@ import SwiftUI
else if let error = model.error { OficinaErrorLine(error) }
}
Section {
+ if let useAnother {
+ Button(OficinaIDText.text("continue.another")) { useAnother() }
+ .buttonStyle(.borderless)
+ .disabled(!canLeave || model.busy)
+ .accessibilityIdentifier("docs.oficinaid.useAnother")
+ }
Button(OficinaIDText.text("otherWays")) { otherWays() }
.buttonStyle(.borderless)
.accessibilityIdentifier("docs.otherWays")
diff --git a/native/apple/Sources/DocsKit/DocsWorkspace.swift b/native/apple/Sources/DocsKit/DocsWorkspace.swift
index 6732e8e..b2777a1 100644
--- a/native/apple/Sources/DocsKit/DocsWorkspace.swift
+++ b/native/apple/Sources/DocsKit/DocsWorkspace.swift
@@ -26,6 +26,9 @@ import SwiftUI
/// "Sign out of <label>". nil keeps the server sign-in's own.
private let accountsLabel: String?
private let signOutLabel: String?
+ /// "Use another Oficina ID" in the account menu (Paul, 2026-11-19); nil
+ /// for a server account, and while it can't be asked.
+ private let useAnother: (() -> Void)?
@Binding private var createRequested: Bool
private let documentID: String?
private let openDocument: ((String, String) -> Void)?
@@ -40,8 +43,8 @@ import SwiftUI
@State private var signOutRefusal: DocsLeaveBlock?
/// `transport` supplies the account's current session to the model on every
/// request; without one the model keeps `client` for its whole lifetime.
- public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), signOutRequested: Binding<Bool> = .constant(false), accountsLabel: String? = nil, signOutLabel: String? = nil, openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) {
- self._signOutRequested = signOutRequested; self.accountsLabel = accountsLabel; self.signOutLabel = signOutLabel
+ public init(client: NativeHTTP, accountID: String? = nil, transport: (@MainActor () -> NativeTransport?)? = nil, accounts: (() -> Void)? = nil, signOut: @escaping () -> Void, documentID: String? = nil, newDocument: Bool = false, createDocument: (() -> Void)? = nil, documentChanged: ((String, String) -> Void)? = nil, canSignOut: Bool = true, createRequested: Binding<Bool> = .constant(false), accountsRequested: Binding<Bool> = .constant(false), signOutRequested: Binding<Bool> = .constant(false), accountsLabel: String? = nil, signOutLabel: String? = nil, useAnother: (() -> Void)? = nil, openDocument: ((String, String) -> Void)? = nil, updateRecents: (([(String, String)]) -> Void)? = nil) {
+ self._signOutRequested = signOutRequested; self.accountsLabel = accountsLabel; self.signOutLabel = signOutLabel; self.useAnother = useAnother
self.updateRecents = updateRecents; self.canSignOut = canSignOut; self._createRequested = createRequested; self._accountsRequested = accountsRequested; self.documentID = documentID; self.openDocument = openDocument
self.newDocument = newDocument; self.createDocument = createDocument; self.documentChanged = documentChanged
self.accountID = accountID
@@ -336,7 +339,8 @@ import SwiftUI
.navigationTitle(docsMacString("Home"))
.searchable(text: $query, prompt: Text("docs.list.search.label", bundle: DocsResources.bundle))
.onSubmit(of: .search) { Task { await model.load(query: query) } }
- .focusedSceneValue(\.docsAccountActions, DocsAccountActions(accounts: accounts, signOut: signOut, canManage: !model.creatingDocument, canSignOut: canSignOut && !model.creatingDocument))
+ .focusedSceneValue(\.docsAccountActions, DocsAccountActions(accounts: accounts, signOut: signOut, canManage: !model.creatingDocument, canSignOut: canSignOut && !model.creatingDocument,
+ useAnother: useAnother, accountsLabel: accountsLabel, signOutLabel: signOutLabel))
.toolbar {
Button(docsMacString("New document"), systemImage: "plus") { beginDocument() }.disabled(!model.canCreate)
}
diff --git a/native/apple/Sources/DocsKit/Resources/Colophon.json b/native/apple/Sources/DocsKit/Resources/Colophon.json
index aac8ed9..6737e3d 100644
--- a/native/apple/Sources/DocsKit/Resources/Colophon.json
+++ b/native/apple/Sources/DocsKit/Resources/Colophon.json
@@ -1737,7 +1737,7 @@
{
"ecosystem": "swift",
"name": "native",
- "version": "f1c7a14db2dd",
+ "version": "1e36aac95ed2",
"notices": [
{
"Name": "LICENSE",
diff --git a/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift b/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift
index 1f33066..6267ba5 100644
--- a/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift
+++ b/native/apple/Tests/DocsKitTests/OficinaIDAdoptionTests.swift
@@ -1,5 +1,8 @@
+import Combine
import CryptoKit
import Foundation
+import Observation
+import Synchronization
import RastrilloApple
import RastrilloNative
import RastrilloTestSupport
@@ -433,6 +436,208 @@ import XCTest
XCTAssertNotEqual(DocsLeaveBlock.sending.message, "native.leave.sending", "the line is translated, not a key")
}
+ // MARK: Straight in (Paul, 2026-11-19; spec §9, rule 0)
+
+ /// Paul on one team with Docs and Sheets, signed in on `device` by
+ /// Sheets: the saved identity Docs finds at launch. A fixture that
+ /// cannot sign in fails the test (never a skip, which would hide what
+ /// depends on it).
+ @discardableResult
+ private func savedIdentity(on device: Device) async throws -> OficinaTeam {
+ let paul = team("t1", "Paul", "paulca", apps: ["docs", "sheets"])
+ service.addPerson(email: "paul@tito.io", identityID: "id-paul")
+ service.setTeams([paul], for: "id-paul")
+ service.admit("id-paul", at: paulca, as: .linked)
+ service.admit("id-paul", at: URL(string: "https://paulca.sheets.oficina.works")!, as: .linked)
+ let clock = self.clock!
+ let sheets = OficinaIDModel(configuration: OficinaIDConfiguration(app: "sheets", appName: "Sheets"),
+ store: OficinaIDStore(shared: device.shared, appPrivate: OficinaMemoryStore(), group: device.group),
+ service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() }, now: { clock.date },
+ appDefaults: defaults())
+ await sheets.start()
+ sheets.continueWithEmail()
+ sheets.email = "paul@tito.io"
+ await sheets.submitEmail()
+ sheets.code = FakeOficinaIDService.goodCode
+ await sheets.submitCode()
+ guard case .signedIn = sheets.step else {
+ XCTFail("Sheets did not sign in: \(sheets.step)")
+ throw CancellationError()
+ }
+ return paul
+ }
+
+ /// One Oficina ID on the device: Docs opens its team with no screen, and
+ /// the launch is not a sign-in made here (the route stays as chosen).
+ func testASavedIdentitySignsDocsStraightIn() async throws {
+ let device = device()
+ let paul = try await savedIdentity(on: device)
+ let docs = session(on: device)
+ var steps: [String] = []
+ let watching = docs.model.$step.sink { steps.append("\($0)".components(separatedBy: "(").first ?? "") }
+ await docs.start()
+ watching.cancel()
+ let mounted = try XCTUnwrap(docs.mounted, "straight in: \(docs.model.step)")
+ XCTAssertEqual(mounted.team, paul)
+ XCTAssertEqual(mounted.origin, paulca)
+ XCTAssertEqual(Set(steps), ["loading", "signedIn"], "no screen on the way in")
+ XCTAssertEqual(docs.signIns, 0, "going straight in does not choose the route")
+ XCTAssertEqual(service.calls.filter { $0.hasPrefix("startCode") }.count, 1, "one sign-in for both apps")
+ XCTAssertNotNil(docs.transport(for: DocsOficinaSession.accountID(mounted))())
+ }
+
+ /// Docs' last route was its own sign-in: nothing goes straight in, and
+ /// nothing touches the network, until the route is Oficina ID again.
+ func testTheServerRouteSuspendsStraightIn() async throws {
+ let device = device()
+ try await savedIdentity(on: device)
+ let docs = session(on: device)
+ let calls = service.calls.count
+ await docs.start(serverRoute: true)
+ XCTAssertTrue(docs.model.straightInSuspended)
+ XCTAssertNil(docs.mounted)
+ XCTAssertEqual(docs.model.step, .welcome)
+ XCTAssertEqual(service.calls.count, calls, "no network while Docs' own sign-in is the route")
+ await docs.routeChanged(to: .oficinaID)
+ XCTAssertFalse(docs.model.straightInSuspended)
+ XCTAssertEqual(docs.mounted?.origin, paulca, "straight in once the route is Oficina ID")
+ XCTAssertEqual(docs.signIns, 0)
+ }
+
+ /// The route alone decides: flipping to the server route while signed
+ /// in suspends straight in and disturbs nothing; flipping back resumes
+ /// without a second sign-in.
+ func testTheRouteAloneDecidesTheSuspension() async throws {
+ let device = device()
+ try await savedIdentity(on: device)
+ let docs = session(on: device)
+ await docs.start()
+ let mounted = try XCTUnwrap(docs.mounted)
+ let exchangesBefore = exchanges(at: paulca)
+ await docs.routeChanged(to: .server)
+ XCTAssertTrue(docs.model.straightInSuspended)
+ XCTAssertEqual(docs.mounted, mounted, "signed in, suspending changes nothing")
+ XCTAssertNotNil(docs.transport(for: DocsOficinaSession.accountID(mounted))(), "the session stays usable")
+ await docs.routeChanged(to: .oficinaID)
+ XCTAssertFalse(docs.model.straightInSuspended)
+ XCTAssertEqual(docs.mounted, mounted)
+ XCTAssertEqual(exchanges(at: paulca), exchangesBefore, "resuming a signed-in model mints nothing")
+ }
+
+ /// "Use another Oficina ID" is asked only while signed in to the
+ /// identity, never with one of its document windows open, never over an
+ /// outage (the team stays mounted, but there is no dialog to ask with).
+ func testUseAnotherIsRefusedWithAnOpenDocumentOrOverAnOutage() async throws {
+ let device = device()
+ let paul = try await savedIdentity(on: device)
+ let docs = session(on: device)
+ await docs.start()
+ let state = try XCTUnwrap(docs.mounted)
+ XCTAssertFalse(docs.useAnother(identity: state.identity.id, canLeave: false), "a document window is open")
+ XCTAssertFalse(docs.model.confirmingReplace)
+ XCTAssertFalse(docs.useAnother(identity: "id-someone-else", canLeave: true), "another identity's menu")
+ XCTAssertFalse(docs.model.confirmingReplace)
+
+ service.expire(session: state.session)
+ service.failNext("exchange", at: paulca.absoluteString, with: .offline)
+ await docs.rejected(DocsOficinaSession.accountID(state))
+ XCTAssertEqual(docs.model.step, .unavailable(paul))
+ XCTAssertNotNil(docs.mounted, "the workspace stays over the outage")
+ XCTAssertFalse(docs.useAnother(identity: state.identity.id, canLeave: true), "over an outage")
+ XCTAssertFalse(docs.model.confirmingReplace)
+
+ await docs.model.retry()
+ XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true))
+ XCTAssertTrue(docs.model.confirmingReplace)
+ }
+
+ /// From the menu it only asks: cancelling changes nothing; confirming
+ /// signs the identity out on every app and goes to Email, and its
+ /// workspaces get no session.
+ func testUseAnotherFromTheMenuAsksThenReplaces() async throws {
+ let device = device()
+ try await savedIdentity(on: device)
+ let docs = session(on: device)
+ await docs.start()
+ let state = try XCTUnwrap(docs.mounted)
+ let account = DocsOficinaSession.accountID(state)
+ XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true))
+ docs.model.cancelReplace()
+ XCTAssertEqual(docs.mounted, state, "cancelling changes nothing")
+ XCTAssertEqual(docs.client(for: account)?.credential?.value, state.session.value)
+ XCTAssertTrue(service.isLive(session: state.session))
+ XCTAssertTrue(docs.useAnother(identity: state.identity.id, canLeave: true))
+ docs.model.confirmReplace()
+ await docs.model.cleanup?.value
+ XCTAssertNil(docs.mounted)
+ XCTAssertEqual(docs.model.step, .email)
+ XCTAssertEqual(try docs.model.store.identities(), [], "signed out on every app")
+ XCTAssertNil(docs.transport(for: account)())
+ }
+
+ /// Docs' guards answer a write with an ended session 403 "signed out"
+ /// (internal/docs/native_contract_test.go): that is the session, not
+ /// the request, so it re-mints and reads as unauthorized. Any other 403
+ /// stays a refusal of the request.
+ func testASignedOut403IsAnEndedSession() async throws {
+ final class Counts: @unchecked Sendable { var rejected = 0, refused = 0 }
+ let counts = Counts()
+ let server = ScriptedTransport([
+ .respond(status: 403, body: Data("signed out\n".utf8)),
+ .respond(status: 403, body: Data("Something went wrong.\n".utf8)),
+ .respond(status: 403, body: Data("signed out".utf8)),
+ ])
+ let watch = DocsSessionWatch(inner: server, rejected: { counts.rejected += 1 }, refused: { counts.refused += 1 })
+ let ended = try await watch.responseDetails("/documents", method: "POST", body: Data("{}".utf8),
+ contentType: "application/json", maxBytes: 1024)
+ XCTAssertEqual(ended.status, 401)
+ XCTAssertEqual(counts.rejected, 1)
+ XCTAssertEqual(counts.refused, 0)
+ for _ in 0..<2 {
+ let refusal = try await watch.responseDetails("/documents", method: "POST", body: Data("{}".utf8),
+ contentType: "application/json", maxBytes: 1024)
+ XCTAssertEqual(refusal.status, 403)
+ }
+ XCTAssertEqual(counts.rejected, 1, "only the exact bytes are an ended session")
+ XCTAssertEqual(counts.refused, 2)
+ }
+
+ /// What the signed-in window's body builds, built under observation as
+ /// a body is: the transport and the workspace, with "Use another". None
+ /// of it may change anything a view watches, or each body pass would
+ /// invalidate the next (84d1008).
+ func testBuildingTheSignedInWorkspaceChangesNothingAViewWatches() async throws {
+ let device = device()
+ try await savedIdentity(on: device)
+ let docs = session(on: device)
+ await docs.start()
+ let state = try XCTUnwrap(docs.mounted)
+ let account = DocsOficinaSession.accountID(state)
+ let offline = DocsOfflineAccount(store: EphemeralDocsStore(), accountID: account,
+ connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)),
+ transport: docs.transport(for: account))
+ DocsOfflineAccount.accounts[account] = offline
+ defer { DocsOfflineAccount.accounts[account] = nil }
+ let client = try XCTUnwrap(docs.client(for: account))
+ var published = 0
+ let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }]
+ let changed = Mutex(false)
+ withObservationTracking {
+ _ = offline.drainer.status()
+ _ = offline.drainer.sessionEnded
+ _ = DocsWorkspace(client: client, accountID: account, transport: docs.transport(for: account), accounts: {}, signOut: {},
+ accountsLabel: DocsOficinaSession.teamsTitle, signOutLabel: "Sign out", useAnother: {})
+ _ = docs.mounted
+ _ = docs.model.step
+ } onChange: { changed.withLock { $0 = true } }
+ for _ in 0..<3 {
+ _ = DocsWorkspace(client: client, accountID: account, transport: docs.transport(for: account), signOut: {}, useAnother: {})
+ }
+ watches.forEach { $0.cancel() }
+ XCTAssertFalse(changed.withLock { $0 }, "building the signed-in workspace must not invalidate its window")
+ XCTAssertEqual(published, 0, "nor publish from the session or the model")
+ }
+
#if os(macOS)
func testTheLaunchCheckFailsWithoutTheEntitlements() {
// The test runner is not signed with Docs' entitlements: every check
diff --git a/native/apple/Tests/DocsWindowTests/SignedInLaunchTests.swift b/native/apple/Tests/DocsWindowTests/SignedInLaunchTests.swift
new file mode 100644
index 0000000..d77cb99
--- /dev/null
+++ b/native/apple/Tests/DocsWindowTests/SignedInLaunchTests.swift
@@ -0,0 +1,150 @@
+#if os(macOS)
+import AppKit
+import Combine
+import Foundation
+import Observation
+import Synchronization
+import SwiftUI
+import XCTest
+import RastrilloApple
+import RastrilloTestSupport
+@testable import DocsKit
+@testable import DocsMac
+
+/// Launching with a saved account (Docs 0.1.7/0.1.8, fixed in 84d1008): the
+/// window's body built a workspace whose init read and then changed state
+/// the body watched, so every pass invalidated the next and the main thread
+/// never came back, but only for someone already signed in. A clean launch
+/// never shows it. These host Docs' real home window with an Oficina ID
+/// already on the device, so Docs goes straight in, let it settle, and check
+/// that it stops changing.
+@MainActor final class SignedInLaunchTests: XCTestCase {
+ /// `.invalid`, so the workspace's first requests fail at once.
+ static let docsOrigin = URL(string: "https://paulca.docs.invalid")!
+ static let sheetsOrigin = URL(string: "https://paulca.sheets.invalid")!
+
+ private var account: String?
+
+ override func tearDown() async throws {
+ if let account { DocsOfflineAccount.accounts[account] = nil }
+ UserDefaults.standard.removeObject(forKey: DocsSignInRoute.key)
+ }
+
+ /// An Oficina ID Sheets saved on this device, and Docs' session after
+ /// going straight in with it. The account's offline store is in memory,
+ /// registered before the window exists: a known account is the path
+ /// that hung.
+ private func signedInSession() async throws -> DocsOficinaSession {
+ let service = FakeOficinaIDService()
+ let shared = OficinaMemoryStore(), notifier = OficinaLocalNotifier()
+ let group = UserDefaults(suiteName: "DocsSignedInLaunchTests.\(UUID().uuidString)")!
+ func model(_ slug: String, _ name: String) -> OficinaIDModel {
+ OficinaIDModel(configuration: OficinaIDConfiguration(app: slug, appName: name, platform: "macos"),
+ store: OficinaIDStore(shared: shared, appPrivate: OficinaMemoryStore(), group: group, notifier: notifier),
+ service: service, passkeys: FakePasskeys(), makeKey: { OficinaSoftwareKey() },
+ appDefaults: UserDefaults(suiteName: "DocsSignedInLaunchTests.\(UUID().uuidString)")!)
+ }
+ let team = OficinaTeam(sqid: "t1", label: "paulca", name: "Paul", role: "member",
+ apps: [OficinaTeamApp(app: "docs", origin: Self.docsOrigin.absoluteString, consumerID: "t1-docs"),
+ OficinaTeamApp(app: "sheets", origin: Self.sheetsOrigin.absoluteString, consumerID: "t1-sheets")])
+ service.addPerson(email: "paul@tito.io", identityID: "id-1")
+ service.setTeams([team], for: "id-1")
+ service.admit("id-1", at: Self.docsOrigin, as: .linked)
+ service.admit("id-1", at: Self.sheetsOrigin, as: .linked)
+ let sheets = model("sheets", "Sheets")
+ await sheets.start()
+ sheets.continueWithEmail()
+ sheets.email = "paul@tito.io"
+ await sheets.submitEmail()
+ sheets.code = FakeOficinaIDService.goodCode
+ await sheets.submitCode()
+ let docs = DocsOficinaSession(model: model("docs", "Docs"))
+ await docs.start()
+ // Failing, not skipping: a skip here would hide the whole launch suite.
+ guard let mounted = docs.mounted else {
+ XCTFail("Docs did not go straight in: \(docs.model.step); Sheets is \(sheets.step)")
+ throw CancellationError()
+ }
+ let account = DocsOficinaSession.accountID(mounted)
+ self.account = account
+ DocsOfflineAccount.accounts[account] = DocsOfflineAccount(
+ store: EphemeralDocsStore(), accountID: account,
+ connectivity: NativeConnectivity(source: ScriptedPathSource(.satisfied)), transport: docs.transport(for: account))
+ UserDefaults.standard.removeObject(forKey: DocsSignInRoute.key)
+ return docs
+ }
+
+ func testTheSignedInHomeWindowSettlesWithASavedIdentity() async throws {
+ let docs = try await signedInSession()
+ let mounted = try XCTUnwrap(docs.mounted)
+ let windows = DocsWindows()
+
+ // If the window loops, the main thread never returns here; say why
+ // rather than hang the run.
+ let finished = Mutex(false)
+ DispatchQueue.global().asyncAfter(deadline: .now() + 60) {
+ if !finished.withLock({ $0 }) {
+ fatalError("Docs' signed-in home window never let the main thread go: a view loop (84d1008)")
+ }
+ }
+ let host = NSHostingView(rootView: DocsAccountWindow(oficina: docs, windows: windows))
+ let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 760), styleMask: [.titled, .resizable],
+ backing: .buffered, defer: false)
+ window.contentView = host
+ window.orderFrontRegardless()
+ defer { window.orderOut(nil); window.contentView = nil }
+
+ func pump(_ seconds: Double) async {
+ let end = Date().addingTimeInterval(seconds)
+ while Date() < end {
+ host.layoutSubtreeIfNeeded()
+ try? await Task.sleep(nanoseconds: 20_000_000)
+ }
+ }
+ // Launch: the body runs, its .task and .onChange(initial:) fire, the
+ // workspace's first request fails at once (.invalid).
+ await pump(1.5)
+ XCTAssertEqual(windows.activeAccount, DocsOficinaSession.accountID(mounted), "the signed-in workspace is what showed")
+ XCTAssertFalse(docs.model.straightInSuspended, "the Oficina ID route does not suspend straight in")
+
+ // Settled: nothing the window watches keeps changing.
+ var published = 0
+ let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }]
+ let invalidated = Mutex(0)
+ withObservationTracking {
+ _ = windows.activeAccount
+ _ = windows.entries
+ _ = windows.accountsRequested
+ _ = windows.settingsAccount
+ _ = windows.settingsIdentity
+ } onChange: { invalidated.withLock { $0 += 1 } }
+ await pump(1.0)
+ watches.forEach { $0.cancel() }
+ finished.withLock { $0 = true }
+ XCTAssertEqual(published, 0, "the session and model stay still once the window has settled")
+ XCTAssertEqual(invalidated.withLock { $0 }, 0, "the window state it writes stays still once settled")
+ XCTAssertEqual(docs.mounted, mounted, "still signed in to the same team")
+ }
+
+ /// The window's body itself, evaluated as SwiftUI would, three times
+ /// over, under observation: building it must change nothing it watches.
+ func testBuildingTheSignedInWindowBodyChangesNothingItWatches() async throws {
+ let docs = try await signedInSession()
+ let windows = DocsWindows()
+ var published = 0
+ let watches = [docs.objectWillChange.sink { _ in published += 1 }, docs.model.objectWillChange.sink { _ in published += 1 }]
+ let changed = Mutex(false)
+ let view = DocsAccountWindow(oficina: docs, windows: windows)
+ withObservationTracking {
+ _ = windows.activeAccount
+ _ = windows.entries
+ _ = windows.transports.count
+ _ = view.body
+ } onChange: { changed.withLock { $0 = true } }
+ for _ in 0..<3 { _ = view.body }
+ watches.forEach { $0.cancel() }
+ XCTAssertFalse(changed.withLock { $0 }, "a body pass must not invalidate the next")
+ XCTAssertEqual(published, 0)
+ }
+}
+#endif
diff --git a/native/ios/project.yml b/native/ios/project.yml
index 5e04e4f..d4480a9 100644
--- a/native/ios/project.yml
+++ b/native/ios/project.yml
@@ -8,7 +8,7 @@ packages:
path: ../apple
RastrilloNative:
url: https://amadan.net/rastrillo/native
- revision: f1c7a14db2ddb8960afabc8268cd92c490543397
+ revision: 1e36aac95ed252848722926efc8ba8f9dc803216
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/macos/project.yml b/native/macos/project.yml
index 3e7c571..46638f1 100644
--- a/native/macos/project.yml
+++ b/native/macos/project.yml
@@ -7,7 +7,7 @@ packages:
path: ../apple
RastrilloNative:
url: https://amadan.net/rastrillo/native
- revision: f1c7a14db2ddb8960afabc8268cd92c490543397
+ revision: 1e36aac95ed252848722926efc8ba8f9dc803216
settings:
base:
SWIFT_VERSION: '6.0'
diff --git a/native/notices/native/provenance.json b/native/notices/native/provenance.json
index 0da081e..c611e5d 100644
--- a/native/notices/native/provenance.json
+++ b/native/notices/native/provenance.json
@@ -1,6 +1,6 @@
{
"comment": "Rastrillo Native's LICENSE, copied unaltered from the checkout SwiftPM resolves for native/apple/Package.resolved (git status clean). internal/shipped refuses it if Package.resolved pins another location or revision.",
"location": "https://amadan.net/rastrillo/native",
- "revision": "f1c7a14db2ddb8960afabc8268cd92c490543397",
+ "revision": "1e36aac95ed252848722926efc8ba8f9dc803216",
"sha256": "d8d2562a7cb68ffdfe91fc66af1ed4a8a4e272aa4ab59bea7451ba34b9aba3d4"
}