//! `unlock.*` — the phone's half of the 15-minute unlock window (sealing plan//! §3.2 steps 3-4, 7-8). The card is decided in the core//! (`cotton_core::rules::unlock`); this file reads the object's rows from the//! copy, answers the card, and posts the answers.//!//! - `unlock.card {}` → `{card, pollSeconds}`: the oldest waiting request as//! the face draws it (`card.face`, `card.fields` by the face's slots, every//! word said by the `unlock` lines; `card.acts` as the face names them), or//! `card: null`; `pollSeconds` is 5 while one waits. In every Cotton app//! signed in to its personal object: every kit pulls the unlock window's//! tables (`rules::SHELL_TABLES`, `AppKit::pulled`), so the card stands from//! the shell wherever the person is. `card.durations` is the choice row//! (`[{minutes, label, on}]`: 15, 60, 1440, 0 = until turned off; the//! request's suggestion on); `card.minutes` is that suggestion.//! - `unlock.allow {requestId, everything?, groups?, tables?, minutes?, privateKey}`://! what it grants is the card's choice: `everything: true` (or nothing//! chosen) every table asked, `groups` the asked tables of the groups picked//! under Choose what (`card.ask.groups`); `tables` is what older builds//! send, the toggles left on. `minutes` any//! of the four (the person's pick wins; the suggestion when absent). The shell//! reads this device's vault key from the Keychain behind Face ID and hands//! it in, as `vault.unlock` takes it. The vault key is opened for this call//! alone: the person key signs through the vault's one signing call, the//! grant is built (every TK up to each table's current seal version,//! and its BK, wrapped to the request's `worker_pub`), signed and posted//! as `unlock_allow`; the vault key and the person key are dropped (wiped)//! before the post, and any open vault session is locked. The versions//! handed are noted (`_unlock_handed`) for the advance.//! On a device whose vault this Allow founds, the founding rule opens//! nothing until the object has taken the wrap: the Allow is then HELD//! ([`HeldAllow`], answered `{held: true, requestId, said}`) with the key it//! was handed, in memory only, and completed by the pass that lands the//! founding ([`after_pass`]), within the request's life; the card says the//! setting-up line meanwhile and offers no act (`rules::Held`).//! - `unlock.decline {requestId}` posts `unlock_decline`.//! - `unlock.end {grantId}` posts `unlock_end`.//! - `unlock.windows {}` → `{windows:[{grantId, requestId, tables, endsAt,//! said, client, standing, connectionId}], acts}`: the windows open now//! (a standing one until it is ended), each row's words, the assistant's//! name, and *End* as the face names it; `heading` is the list's own//! title (`windows.heading`), the Account page's Open access card.//! - `unlock.reads {}` → `{reads:[{id, grantId, client, tables, tool, rows,//! readAt, said}], heading, none}`: the clear read log (`assistant_read`),//! newest first, at most 50, each `{client} read {n} rows of {tables} ·//! {when}`; `heading` and `none` are the list's own words.//!//! After every pass ([`after_pass`]): every table this phone handed keys for//! whose window has ended moves to its next seal version (`seal_key`//! `v:<table>`), once; and while a request waits the phone syncs again in//! five seconds.//!//! Refusals are by name: `request_not_waiting`, `bad_tables`, `bad_minutes`,//! `seal_key_missing`, `vault_locked`, `no_person_key`, and the object's own.use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engineas _;use serde_json::{json, Map, Value};use cotton_core::rules::unlock as rules;use cotton_core::seal::grant::{bundle, bundle_json, unlock_statement, Grant};usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::shell::client::ClientController;/// Every method this family answers.pubconst METHODS: [&str; 7] = ["unlock.allow", "unlock.allowAll", "unlock.card", "unlock.decline", "unlock.end", "unlock.reads", "unlock.windows"];/// The copy's tables the object's unlock rows land in (served definitions).pub(crate) const REQUESTS: &str = "cotton_unlock_request";pub(crate) const GRANTS: &str = "cotton_unlock_grant";pub(crate) const READS: &str = "cotton_assistant_read";/// What this phone handed in each grant: the newest version of each table.const HANDED: &str = "CREATE TABLE IF NOT EXISTS _unlock_handed (request_id TEXT NOT NULL, tbl TEXT NOT NULL, v INTEGER NOT NULL, PRIMARY KEY (request_id, tbl)) WITHOUT ROWID";pubfn call(handle: &CottonHandle, method: &str, request: &Value) -> Result<Value, MethodError> { call_on(&handle.client(), method, request)}pub(crate) fn call_on(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"unlock.card" => card(client),"unlock.allow" => allow(client, request),"unlock.allowAll" => allow_all(client, request),"unlock.decline" => {let request_id = text_arg(request, "requestId")?; post(client, "unlock_decline", json!({ "request_id": request_id }))?;Ok(json!({ "declined": request_id })) }"unlock.end" => {let grant_id = text_arg(request, "grantId")?; post(client, "unlock_end", json!({ "grant_id": grant_id }))?; client.nudge_sync();Ok(json!({ "ended": grant_id })) }"unlock.windows" => windows(client),"unlock.reads" => reads(client), _ => Err(MethodError::new("unknown_method", format!("`{method}` is not an unlock method"))), }}pub(crate) fn text_arg(request: &Value, name: &str) -> Result<String, MethodError> { request[name].as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string).ok_or_else(|| MethodError::new("bad_request", format!("this call needs `{name}`")))}pub(crate) fn unreadable(why: String) -> MethodError {MethodError::new("could_not_read", why)}/// The personal copy's file, read-only.pub(crate) fn copy(client: &ClientController) -> Result<(String, rusqlite::Connection), MethodError> {let database = {let _personal = client.name_database(None).map_err(unreadable)?; client.current_database().map_err(unreadable)? };let path = client.layout().replica(&database);let file = rusqlite::Connection::open_with_flags(&path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX) .map_err(|error| unreadable(format!("this phone's copy could not be read ({error})")))?;Ok((database, file))}/// Every row of a served table as JSON (its columns by key), or none when/// the copy has not made the table yet.pub(crate) fn rows(file: &rusqlite::Connection, table: &str) -> Result<Vec<Value>, MethodError> {let fail = |error: rusqlite::Error| unreadable(format!("{table} could not be read ({error})"));let exists: bool = file.query_row("SELECT count(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", [table], |row| row.get::<_, i64>(0)).map_err(fail)? > 0;if !exists {returnOk(Vec::new()); }letmut statement = file.prepare(&format!("SELECT * FROM {table}")).map_err(fail)?;let names: Vec<String> = statement.column_names().map(str::to_string).collect();let found = statement .query_map([], |row| {letmut out = Map::new();for (i, name) in names.iter().enumerate() {let value = match row.get_ref(i)? { rusqlite::types::ValueRef::Null => Value::Null, rusqlite::types::ValueRef::Integer(n) => Value::from(n), rusqlite::types::ValueRef::Real(f) => Value::from(f), rusqlite::types::ValueRef::Text(t) => Value::from(String::from_utf8_lossy(t).into_owned()), rusqlite::types::ValueRef::Blob(_) => Value::Null, }; out.insert(name.clone(), value); }Ok(Value::Object(out)) }) .map_err(fail)? .collect::<Result<Vec<_>, _>>() .map_err(fail)?;Ok(found)}/// What the card calls a table: its plural as the object defines it (the/// served definitions the copy keeps, so a table the owner made or the object/// added is named too; else the object's last served answer the passes hold,/// for a table this copy keeps nowhere: a Keys copy keeps only its kit's),/// else the kit's shipped definition's; a table none names shows its id.pub(crate) fn labels(client: &ClientController, database: &str) -> implFn(&str) -> Option<String> {let held = client.served_definitions();let served: std::collections::BTreeMap<String, String> = cotton_client::transport::object::object_definitions(&client.layout().replica(database)) .unwrap_or_default() .into_iter() .filter_map(|definition| Some((definition["id"].as_str()?.to_string(), definition["plural"].as_str().filter(|plural| !plural.is_empty())?.to_string()))) .collect();move |table: &str| served.get(table).cloned().or_else(|| held.as_ref().and_then(|held| held.plural(table))).or_else(|| cotton_core::kit::shipped_table(table).map(|definition| definition.plural.clone()).filter(|plural| !plural.is_empty()))}/// Whether this app shows the card at all: it keeps a personal copy the/// object's requests land in. Every kit pulls them (ruling R4: the card/// stands from the shell in whatever Cotton app is open).fn shown_here(client: &ClientController) -> Result<bool, MethodError> {Ok(client.require_personal().is_ok())}/// The card's words: the database's own `unlock` lines over the kit's.pub(crate) fn lines_of(client: &ClientController) -> Result<cotton_core::rules::shell_lines::LineSet, MethodError> { lines(client)}fn lines(client: &ClientController) -> Result<cotton_core::rules::shell_lines::LineSet, MethodError> {let rows = crate::phone::records::line_rows_kept(client); cotton_core::rules::shell_lines::LineSet::of_rows(rules::LINES, &rows).ok_or_else(|| unreadable("the unlock lines are not in this build".into()))}fn card(client: &ClientController) -> Result<Value, MethodError> {if !shown_here(client)? {returnOk(json!({ "card": null, "pollSeconds": null })); }let (database, file) = copy(client)?;let requests = rows(&file, REQUESTS)?;let now = client.now();let held = client.unlock_held();let card = rules::card_held(&requests, now, labels(client, &database), &lines(client)?, held.as_ref().map(HeldAllow::rule)); drop(held);Ok(json!({ "card": card, "pollSeconds": rules::poll_seconds(&requests, now) }))}fn windows(client: &ClientController) -> Result<Value, MethodError> {let acts = rules::window_acts();let lines = lines(client)?;let heading = lines.say("windows.heading", &[]).unwrap_or_default();if !shown_here(client)? {returnOk(json!({ "windows": [], "acts": acts, "heading": heading })); }let (database, file) = copy(client)?;let now = client.now();let label = labels(client, &database);let open: Vec<Value> = rows(&file, GRANTS)? .into_iter() .filter(|grant| rules::grant_open(grant, now)) .map(|grant| {let tables = list(&grant["tables"]);let said = rules::grant_said(&grant, now, &label, &lines); json!({"grantId": grant["id"], "requestId": grant["request_id"], "tables": tables, "endsAt": grant["ends_at"], "said": said,"client": grant["client"], "standing": rules::grant_standing(&grant), "connectionId": grant["connection_id"], }) }) .collect();Ok(json!({ "windows": open, "acts": acts, "heading": heading }))}fn reads(client: &ClientController) -> Result<Value, MethodError> {let lines = lines(client)?;let said = |line: &str| lines.say(line, &[]).unwrap_or_default();let (heading, none) = (said("reads.heading"), said("reads.none"));if !shown_here(client)? {returnOk(json!({ "reads": [], "heading": heading, "none": none })); }let (database, file) = copy(client)?;let read = rules::reads(&rows(&file, READS)?, client.now(), labels(client, &database), &lines);Ok(json!({ "reads": read, "heading": heading, "none": none }))}fn list(value: &Value) -> Vec<String> {let value = match value {Value::String(text) => serde_json::from_str(text).unwrap_or(Value::Null), other => other.clone(), }; value.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()}pub(crate) fn post(client: &ClientController, act: &str, args: Value) -> Result<Value, MethodError> {let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "an unlock request is answered on the object: sign in first"))?; door.send("POST", cotton_client::transport::object::routes::ACT, Some(&json!({ "act": act, "args": args })))}/// An Allow taken on the card and not posted yet: held while this device's/// vault founds, with the device key it was handed (wiped on drop), or the/// sentence that refused completing it. One at a time: a card stands for one/// request.pubenumHeldAllow {Pending { request_id: String, tables: Option<Vec<String>>, minutes: Option<u32>, secret: zeroize::Zeroizing<[u8; 32]> },/// Its grant going up now: the card still says the setting-up line and/// offers no act, so nobody taps Allow a second time while it posts.Posting { request_id: String },Failed { request_id: String, sentence: String },}implHeldAllow {fn request_id(&self) -> &str {matchself {HeldAllow::Pending { request_id, .. } | HeldAllow::Posting { request_id } | HeldAllow::Failed { request_id, .. } => request_id, } }fn rule(&self) -> rules::Held<'_> {matchself {HeldAllow::Pending { request_id, .. } | HeldAllow::Posting { request_id } => rules::Held::Pending(request_id),HeldAllow::Failed { request_id, sentence } => rules::Held::Failed { request_id, sentence }, } }}fn allow(client: &ClientController, request: &Value) -> Result<Value, MethodError> {ifletSome(sentence) = client.write_refusal() {returnErr(MethodError::new("refused", sentence)); }let request_id = text_arg(request, "requestId")?;letmut chosen: Option<Vec<String>> = request.get("tables").filter(|v| !v.is_null()).map(|v| v.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect());// The card's plain choice: `everything` (or nothing said) is every table asked; `groups` the groups picked under// Choose what, each its asked tables (`rules::chosen_tables`). It wins over `tables`, which older builds send.if request.get("everything").and_then(Value::as_bool) == Some(true) || request.get("groups").is_some_and(|v| !v.is_null()) {let groups: Option<Vec<String>> = request.get("groups").filter(|v| !v.is_null() && request.get("everything").and_then(Value::as_bool) != Some(true)).map(|v| v.as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect());let (_, file) = copy(client)?;let asked = rows(&file, REQUESTS)? .iter() .filter_map(rules::request_of) .find(|r| r.id == request_id) .ok_or_else(|| MethodError::new(rules::AnswerRefusal::NotWaiting.code(), rules::AnswerRefusal::NotWaiting.sentence()))?; drop(file); chosen = Some(rules::chosen_tables(&asked, groups.as_deref()).map_err(|refusal| MethodError::new(refusal.code(), refusal.sentence()))?); }let minutes = request.get("minutes").and_then(Value::as_u64).map(|m| u32::try_from(m).unwrap_or(u32::MAX));let secret = zeroize::Zeroizing::new(crate::phone::vault::private_key_arg(request)?); *client.unlock_held() = None;match allow_now(client, &request_id, chosen.as_deref(), minutes, &secret) {Err(refusal) if refusal.code == "vault_not_wrapped_yet" && crate::phone::vault::founding_waits(client)? => { *client.unlock_held() = Some(HeldAllow::Pending { request_id: request_id.clone(), tables: chosen, minutes, secret }); client.nudge_sync();Ok(json!({ "held": true, "requestId": request_id, "said": lines(client)?.say("setting_up", &[]).unwrap_or_default() })) } answer => answer, }}/// *Allow all* (owner, 23 Nov 2026: three cards from his own machines came one after another): each named request/// that still waits and is a timed ask of the person's own Claude Code machines is allowed as asked (every table/// it asked, its own suggested time), one phone lock for all. Anything else named is left to its own card. The/// answer counts what was allowed and says why any was not.fn allow_all(client: &ClientController, request: &Value) -> Result<Value, MethodError> {ifletSome(sentence) = client.write_refusal() {returnErr(MethodError::new("refused", sentence)); }let named: Vec<String> = request.get("requestIds").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();if named.is_empty() {returnErr(MethodError::new("bad_request", "requestIds names the requests Allow all answers")); }let secret = zeroize::Zeroizing::new(crate::phone::vault::private_key_arg(request)?);let (_, file) = copy(client)?;let asked = rules::allow_all_ids(&rows(&file, REQUESTS)?, client.now(), &named); drop(file);if asked.is_empty() {returnErr(MethodError::new(rules::AnswerRefusal::NotWaiting.code(), rules::AnswerRefusal::NotWaiting.sentence())); } *client.unlock_held() = None;letmut allowed: Vec<String> = Vec::new();letmut refused: Vec<Value> = Vec::new();for r in &asked {match allow_now(client, &r.id, None, None, &secret) {Ok(_) => allowed.push(r.id.clone()),// The vault still being set up stops them all alike: said once, as Allow says it.Err(refusal) if allowed.is_empty() && refusal.code == "vault_not_wrapped_yet" => returnErr(refusal),Err(refusal) => refused.push(json!({ "requestId": r.id, "code": refusal.code, "said": refusal.message })), } }Ok(json!({ "allowed": allowed, "refused": refused }))}/// The Allow itself: the grant built, signed and posted, or refused by name.fn allow_now(client: &ClientController, request_id: &str, chosen: Option<&[String]>, minutes: Option<u32>, secret: &[u8; 32]) -> Result<Value, MethodError> {let (database, file) = copy(client)?;let asked = rows(&file, REQUESTS)? .iter() .filter_map(rules::request_of) .find(|r| r.id == request_id) .ok_or_else(|| MethodError::new(rules::AnswerRefusal::NotWaiting.code(), rules::AnswerRefusal::NotWaiting.sentence()))?;let (tables, minutes) = rules::allowed(&asked, client.now(), chosen, minutes).map_err(|refusal| MethodError::new(refusal.code(), refusal.sentence()))?;let worker_pub: [u8; 32] = URL_SAFE_NO_PAD .decode(asked.worker_pub.trim_end_matches('=')) .ok() .and_then(|bytes| bytes.try_into().ok()) .ok_or_else(|| MethodError::new("bad_request", "the request's worker key is not a 32-byte key"))?;// Each table at its current seal version: the sealer's word, which has// learned every seal_key row this copy keeps.let sealer = crate::phone::personal_object::sealer_of(client, &database);for (id, data) in cotton_client::seal::kept_keys(&file).map_err(unreadable)? { sealer.learn(&id, &data); } drop(file);let versions: Vec<(String, u32)> = tables.iter().map(|t| (t.clone(), sealer.version(t))).collect();// The one card for your Claude: the standing grant to its member key.if asked.account {returncrate::phone::assistants::allow_card(client, &database, &asked, &versions, secret); }// The vault key opens for this call alone: the person key signs through// the vault's one signing call, then every vault session is locked, so// neither key outlives the signature (no five-minute wait).let grant = {let (vmk, version) = crate::phone::vault::opened_vmk(client, secret)?;crate::phone::person_key::ensure(client, &vmk, version)?;// The grant wraps table keys the DK derives: held already, or taken now while the vault is open.let dk = crate::phone::seal::ensure(client, &vmk, version)?; client.vault().map_err(unreadable)?.unlock(vmk, version, client.now());let signed = sign_grant(client, &dk, &database, &asked, &versions, minutes, &worker_pub); client.vault_session().lock_all(); signed? }; note_handed(client, &database, &asked.id, &versions)?;let answer = post(client, "unlock_allow", json!({ "request_id": asked.id, "tables": grant.tables, "minutes": grant.minutes, "wrapped": grant.wrapped, "signer": grant.signer, "sig": grant.sig }))?; client.nudge_sync();Ok(json!({ "grantId": answer["grant"], "endsAt": answer["ends_at"], "tables": grant.tables, "minutes": grant.minutes }))}/// The grant (sealing plan §3.2 step 4): every TK up to each table's/// version and its BK, wrapped to the request's `worker_pub`, and the unlock/// statement signed by the person key (the vault's signing call, which/// needs the vault open).fn sign_grant(client: &ClientController, dk: &cotton_core::seal::DataKey, database: &str, asked: &rules::UnlockRequest, versions: &[(String, u32)], minutes: u32, worker_pub: &[u8; 32]) -> Result<Grant, MethodError> {let sealing = |error: cotton_core::seal::SealError| MethodError::new(error.code(), error.to_string());let keys = bundle(dk, database, &asked.id, &asked.token_id, versions).map_err(sealing)?;let wrapped = cotton_core::vault::wrap::wrap(worker_pub, bundle_json(&keys).as_bytes()).ok_or_else(|| MethodError::new("bad_request", "the request's worker key cannot take a wrap"))?; drop(keys);let tables: Vec<String> = versions.iter().map(|(t, _)| t.clone()).collect();let statement = unlock_statement(database, &asked.id, &asked.token_id, &tables, minutes, &wrapped).map_err(sealing)?;let (public_key, sig) = crate::phone::vault::sign_as_person(client, &statement)?;let signer = cotton_core::keys::person::fingerprint(&public_key).ok_or_else(|| MethodError::new("no_person_key", "the person key is unreadable"))?;letmut sorted = tables; sorted.sort();Ok(Grant { tables: sorted, minutes, wrapped, signer, sig: URL_SAFE_NO_PAD.encode(sig) })}pub(crate) fn writable(client: &ClientController, database: &str) -> Result<rusqlite::Connection, MethodError> {let path = client.layout().replica(database);let file = rusqlite::Connection::open(&path).map_err(|error| unreadable(format!("this phone's copy could not be opened ({error})")))?; file.busy_timeout(std::time::Duration::from_secs(5)).map_err(|error| unreadable(error.to_string()))?; file.execute(HANDED, []).map_err(|error| unreadable(error.to_string()))?;Ok(file)}pub(crate) fn note_handed(client: &ClientController, database: &str, request_id: &str, versions: &[(String, u32)]) -> Result<(), MethodError> {let file = writable(client, database)?;for (table, v) in versions { file.execute("INSERT INTO _unlock_handed (request_id, tbl, v) VALUES (?1, ?2, ?3) ON CONFLICT (request_id, tbl) DO UPDATE SET v = excluded.v", rusqlite::params![request_id, table, v]) .map_err(|error| unreadable(error.to_string()))?; }Ok(())}/// After a pass: advance every table whose window ended (once each), and/// sync again soon while a request waits. Errors are logged; the next pass/// asks again.pubfn after_pass(client: &Arc<ClientController>) {if !client.signed_in() || client.object_door().is_none() || client.require_personal().is_err() { *client.unlock_held() = None;return; } complete_held(client);ifletErr(refusal) = crate::phone::assistants::top_up(client) { tracing::warn!("assistants: your Claude's grant was not topped up — {}. It is tried again on the next pass.", refusal.message); }// The passwords the Worker still seals under its own key move under the vault key while the vault is open.ifletErr(refusal) = crate::phone::passwords::rewrap(client) { tracing::warn!("passwords: the ones saved over MCP did not move under the vault key — {}. They are asked again on the next pass.", refusal.message); }ifletErr(refusal) = advance_ended(client) { tracing::warn!("unlock: a sealed table did not move to its next key version — {}. It is asked again on the next pass.", refusal.message); }match copy(client).and_then(|(_, file)| rows(&file, REQUESTS)) {Ok(requests) => {ifletSome(seconds) = rules::poll_seconds(&requests, client.now()) { soon(client, seconds); } }Err(refusal) => tracing::warn!("unlock: the requests could not be read — {}", refusal.message), }}/// The held Allow, after a pass: dropped (its key wiped) once its request no/// longer waits; kept while the founding is still queued; else posted now,/// so the window opens without a second tap. Completing it refused keeps the/// sentence for the card, which offers the acts again.pub(crate) fn complete_held(client: &ClientController) {letSome(held) = client.unlock_held().take() else { return };let waiting = copy(client).and_then(|(_, file)| rows(&file, REQUESTS)).map(|requests| rules::keep_held(&requests, client.now(), held.request_id()));match waiting {Ok(true) => {}Ok(false) => return,Err(refusal) => { tracing::warn!("unlock: the requests could not be read — {}", refusal.message); *client.unlock_held() = Some(held);return; } }letHeldAllow::Pending { request_id, tables, minutes, secret } = held else { *client.unlock_held() = Some(held);return; };let waits = |client: &ClientController| crate::phone::vault::founding_waits(client).unwrap_or(false);if waits(client) { *client.unlock_held() = Some(HeldAllow::Pending { request_id, tables, minutes, secret });return; } *client.unlock_held() = Some(HeldAllow::Posting { request_id: request_id.clone() });let posted = allow_now(client, &request_id, tables.as_deref(), minutes, &secret); *client.unlock_held() = None;match posted {Ok(_) => {}Err(refusal) if refusal.code == "vault_not_wrapped_yet" && waits(client) => { *client.unlock_held() = Some(HeldAllow::Pending { request_id, tables, minutes, secret }); }Err(refusal) => { tracing::warn!("unlock: the held Allow could not be completed — {}", refusal.message); *client.unlock_held() = Some(HeldAllow::Failed { request_id, sentence: refusal.message }); } }}/// One waiting nudge at a time.static POLLING: AtomicBool = AtomicBool::new(false);fn soon(client: &Arc<ClientController>, seconds: u64) {if POLLING.swap(true, Ordering::SeqCst) {return; }let weak = Arc::downgrade(client);let spawned = std::thread::Builder::new().name("cotton-unlock-poll".into()).spawn(move || { std::thread::sleep(std::time::Duration::from_secs(seconds)); POLLING.store(false, Ordering::SeqCst);ifletSome(client) = weak.upgrade() { client.nudge_sync(); } });if spawned.is_err() { POLLING.store(false, Ordering::SeqCst); }}/// For every ended grant this phone handed keys for: each table whose seal/// version has not moved past what was handed moves to its next (posted as/// the `seal_key` act, taken by the sealer at once), then the note goes.pub(crate) fn advance_ended(client: &ClientController) -> Result<Vec<String>, MethodError> {let (database, file) = copy(client)?;let ended: Vec<String> = rows(&file, GRANTS)?.into_iter().filter(rules::grant_ended).filter_map(|grant| grant["request_id"].as_str().map(str::to_string)).collect();if ended.is_empty() {returnOk(Vec::new()); }let sealer = crate::phone::personal_object::sealer_of(client, &database);for (id, data) in cotton_client::seal::kept_keys(&file).map_err(unreadable)? { sealer.learn(&id, &data); } drop(file);let notes = writable(client, &database)?;letmut moved = Vec::new();for request_id in ended {let handed: Vec<(String, u32)> = {letmut statement = notes.prepare("SELECT tbl, v FROM _unlock_handed WHERE request_id = ?1").map_err(|error| unreadable(error.to_string()))?;let found = statement .query_map([&request_id], |row| Ok((row.get::<_, String>(0)?, row.get::<_, u32>(1)?))) .map_err(|error| unreadable(error.to_string()))? .collect::<Result<Vec<_>, _>>() .map_err(|error| unreadable(error.to_string()))?; found };if handed.is_empty() {continue; }for table in rules::to_advance(&handed, |t| sealer.version(t)) {let act = sealer.advance(&table);let door = client.object_door().ok_or_else(|| MethodError::new("sign_in_first", "signed out"))?; door.send("POST", cotton_client::transport::object::routes::ACT, Some(&act))?; moved.push(table); } notes.execute("DELETE FROM _unlock_handed WHERE request_id = ?1", [&request_id]).map_err(|error| unreadable(error.to_string()))?; }Ok(moved)}#[cfg(test)]#[path = "unlock_tests.rs"]pub(crate) mod tests;