fix: take an artifact edit only when made on the latest version's text

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guilhem LemouelandClaude Opus 5.5 committed 2026-11-11 02:56:19 -08:00
1 parent 26613b32da
commit 02f5535510
15 files changed
+517 -244

No files matched your search

@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE ai_artifact SET\n pinned = $4, shown_version = $5, content = $6, name = $7, updated_at = now()\n WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND deleted_at IS NULL\n AND CASE WHEN $4 THEN $5 <= latest_version ELSE $5 = latest_version END\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"query": "UPDATE ai_artifact SET\n session_id = COALESCE(session_id, $3),\n extra_perms = CASE WHEN deleted_at IS NULL THEN extra_perms ELSE '{}'::jsonb END,\n deleted_at = NULL\n WHERE workspace_id = $1 AND artifact_id = $2\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"describe": {
"columns": [
{
@@ -83,10 +83,6 @@
"Left": [
"Text",
"Text",
"Text",
"Bool",
"Int4",
"Text",
"Varchar"
]
},
@@ -108,5 +104,5 @@
true
]
},
"hash": "28e0be2d0e9271f5478725bbd9aa60257b58f98f6c72c63f647721f30ea1313f"
"hash": "30f182f81cb0732cf37a4b1d8e54e0b4e0897b0ff30622d20cbf979ebd5e2193"
}
@@ -1,24 +0,0 @@
{
"db_name": "PostgreSQL",
"query": "SELECT latest_version FROM ai_artifact\n WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND deleted_at IS NULL",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "latest_version",
"type_info": "Int4"
}
],
"parameters": {
"Left": [
"Text",
"Text",
"Text"
]
},
"nullable": [
false
]
},
"hash": "516fb1399b23667ef992dfbb97a4d356f6c8e912a21bf0881d8b423f957b624e"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "INSERT INTO ai_artifact\n (workspace_id, artifact_id, path, email, created_by, session_id, name, kind,\n role, shown_version, content, latest_version)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $10)\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"query": "INSERT INTO ai_artifact\n (workspace_id, artifact_id, path, email, created_by, session_id, name, kind,\n role, shown_version, content, latest_version, latest_hash)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $10, $12)\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"describe": {
"columns": [
{
@@ -91,7 +91,8 @@
"Varchar",
"Varchar",
"Int4",
"Text"
"Text",
"Varchar"
]
},
"nullable": [
@@ -112,5 +113,5 @@
true
]
},
"hash": "d1feb23148bc06398e40e6b812e73ed325f197be17c5e1fd28847cb49c25f8a2"
"hash": "5834cf8b95eb586c6202f1c36a9f40fb6e1fbab37d67637f967b25afe90bbb67"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE ai_artifact SET\n content = CASE WHEN NOT pinned AND $3 > latest_version THEN $4 ELSE content END,\n name = CASE WHEN NOT pinned AND $3 > latest_version THEN $5 ELSE name END,\n updated_at = CASE WHEN NOT pinned AND $3 > latest_version THEN now() ELSE updated_at END,\n shown_version = CASE WHEN NOT pinned AND $3 > latest_version THEN $3 ELSE shown_version END,\n latest_version = GREATEST(latest_version, $3),\n session_id = COALESCE(session_id, $6),\n extra_perms = CASE WHEN deleted_at IS NULL THEN extra_perms ELSE '{}'::jsonb END,\n deleted_at = NULL\n WHERE workspace_id = $1 AND artifact_id = $2\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"query": "UPDATE ai_artifact SET\n pinned = $4,\n shown_version = CASE WHEN $4 THEN $5 ELSE latest_version END,\n content = $6, name = $7, updated_at = now()\n WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND deleted_at IS NULL\n AND latest_hash = $8 AND (NOT $4 OR $5 <= latest_version)\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"describe": {
"columns": [
{
@@ -83,10 +83,12 @@
"Left": [
"Text",
"Text",
"Text",
"Bool",
"Int4",
"Text",
"Varchar",
"Varchar"
"Text"
]
},
"nullable": [
@@ -107,5 +109,5 @@
true
]
},
"hash": "171ff3665fbd55b63253f889831cb81b5d373e52b736636f04d7abb5f7daae54"
"hash": "6693d160cc3bd863b89d933c56ee0a8ec64545f36059eeba7ce78758e439d25f"
}
@@ -0,0 +1,30 @@
{
"db_name": "PostgreSQL",
"query": "SELECT latest_version AS version, latest_hash AS hash FROM ai_artifact\n WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND deleted_at IS NULL",
"describe": {
"columns": [
{
"ordinal": 0,
"name": "version",
"type_info": "Int4"
},
{
"ordinal": 1,
"name": "hash",
"type_info": "Varchar"
}
],
"parameters": {
"Left": [
"Text",
"Text",
"Text"
]
},
"nullable": [
false,
false
]
},
"hash": "6e3a4089b387388e76718cfba98ee95d4e7a327e45f5ffba64eb4752efea8619"
}
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
"query": "UPDATE ai_artifact SET\n latest_version = $4,\n content = CASE WHEN pinned THEN content ELSE $5 END,\n name = CASE WHEN pinned THEN name ELSE $6 END,\n shown_version = CASE WHEN pinned THEN shown_version ELSE $4 END,\n updated_at = CASE WHEN pinned THEN updated_at ELSE now() END,\n session_id = COALESCE(session_id, $8)\n WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND latest_version = $7\n AND deleted_at IS NULL\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"query": "UPDATE ai_artifact SET\n latest_version = GREATEST(latest_version + 1, $4),\n latest_hash = $9,\n content = CASE WHEN pinned THEN content ELSE $5 END,\n name = CASE WHEN pinned THEN name ELSE $6 END,\n shown_version = CASE WHEN pinned THEN shown_version ELSE GREATEST(latest_version + 1, $4) END,\n updated_at = CASE WHEN pinned THEN updated_at ELSE now() END,\n session_id = COALESCE(session_id, $8)\n WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND latest_hash = $7\n AND deleted_at IS NULL\n RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,\n role, shown_version, latest_version, pinned, created_at, updated_at,\n deleted_at",
"describe": {
"columns": [
{
@@ -87,7 +87,8 @@
"Int4",
"Text",
"Varchar",
"Int4",
"Text",
"Varchar",
"Varchar"
]
},
@@ -109,5 +110,5 @@
true
]
},
"hash": "3ffba03f6d7be24c9f2518a1fc1fb0322d80b531b4111eed6bf9795d1467ac45"
"hash": "8761dd76350f03a4fb6f98a2d454aaadb900b224e50b6ffc7df7a65545502da3"
}
@@ -19,9 +19,12 @@ CREATE TABLE ai_artifact (
-- The version people with access see, and its text.
shown_version INTEGER NOT NULL,
content TEXT NOT NULL,
-- The newest version the owner wrote. Above `shown_version` only while `pinned`; writes are
-- refused unless they name it as their base, which is what stops a stale copy overwriting.
-- The newest version the owner wrote. Above `shown_version` only while `pinned`.
latest_version INTEGER NOT NULL,
-- The SHA-256 of that version's text, kept while an older one is pinned. A write is refused
-- unless it was made on this text: two of the owner's browsers can each hold a different
-- text under the same version number.
latest_hash VARCHAR(64) NOT NULL,
pinned BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
-- When `content` last changed.
@@ -89,14 +92,15 @@ USING (exists(
-- AI_SHARED_ARTIFACT_RETENTION_SECS were already deleted by the monitor.
INSERT INTO ai_artifact (
id, workspace_id, artifact_id, path, extra_perms, email, created_by, name, kind,
shown_version, content, latest_version, pinned, created_at, updated_at
shown_version, content, latest_version, latest_hash, pinned, created_at, updated_at
)
SELECT
s.id, s.workspace_id, s.artifact_id,
'u/' || s.created_by || '/' || s.slug
|| CASE WHEN s.rn > 1 THEN '_' || left(replace(s.id::text, '-', ''), 8) ELSE '' END,
'{"g/all": false}'::jsonb, s.email, s.created_by, s.name, s.kind,
s.version, s.content, s.version, true, s.shared_at, s.shared_at
s.version, s.content, s.version, encode(sha256(convert_to(s.content, 'UTF8')), 'hex'), true,
s.shared_at, s.shared_at
FROM (
SELECT a.*, row_number() OVER (
PARTITION BY a.workspace_id, a.created_by, a.slug ORDER BY a.shared_at, a.id
+33 -11
View File
@@ -2,12 +2,17 @@
//! only their owner writes, and which nobody else reads while they are in the owner's trash.
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
const OWNER: &str = "Bearer SECRET_TOKEN_2";
const VIEWER: &str = "Bearer SECRET_TOKEN_3";
fn sha256(text: &str) -> String {
hex::encode(Sha256::digest(text.as_bytes()))
}
struct Api {
client: reqwest::Client,
base: String,
@@ -105,7 +110,7 @@ async fn an_artifact_reaches_its_access_list_until_it_is_trashed(
.post(
"ai/artifacts/write/a1",
VIEWER,
json!({ "base_version": 1, "version": 2, "name": "Plan", "content": "vandalized" }),
json!({ "base_hash": sha256("draft"), "version": 2, "name": "Plan", "content": "vandalized" }),
)
.await?;
assert_eq!(body["outcome"], "not_shared", "a viewer wrote the artifact");
@@ -136,29 +141,46 @@ async fn an_artifact_reaches_its_access_list_until_it_is_trashed(
}
#[sqlx::test(fixtures("base"))]
async fn a_write_based_on_an_older_version_is_refused(db: Pool<Postgres>) -> anyhow::Result<()> {
async fn a_change_made_on_another_text_is_refused(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
let server = ApiServer::start(db.clone()).await?;
let api = Api::new(&server);
api.publish("draft").await?;
let write = |content: &str| json!({ "base_version": 1, "version": 2, "name": "Plan", "content": content });
let write = |base: &str, version: i32, content: &str| json!({ "base_hash": sha256(base), "version": version, "name": "Plan", "content": content });
let (_, body) = api
.post("ai/artifacts/write/a1", OWNER, write("first"))
.post("ai/artifacts/write/a1", OWNER, write("draft", 2, "first"))
.await?;
assert_eq!(body["outcome"], "saved", "{body}");
let (_, body) = api
.post("ai/artifacts/write/a1", OWNER, write("second"))
.await?;
assert_eq!(body["outcome"], "stale", "{body}");
assert_eq!(body["latest_version"], 2);
// Made on the text the first write replaced, and on another browser's own version 2.
for stale in [write("draft", 2, "second"), write("theirs", 3, "second")] {
let (_, body) = api.post("ai/artifacts/write/a1", OWNER, stale).await?;
assert_eq!(body["outcome"], "stale", "{body}");
assert_eq!(body["latest_version"], 2);
assert_eq!(body["latest_hash"], sha256("first"));
}
let (_, body) = api.get("ai/artifacts/get/a1", OWNER).await?;
assert_eq!(
body["content"], "first",
"a stale write overwrote a newer version"
);
// A browser numbering below the latest gets the next number above it.
let (_, body) = api
.post("ai/artifacts/write/a1", OWNER, write("first", 2, "third"))
.await?;
assert_eq!(body["latest_version"], 3, "{body}");
let pin = |base: &str| json!({ "pinned": true, "version": 1, "name": "Plan", "content": "draft", "base_hash": sha256(base) });
let (_, body) = api
.post("ai/artifacts/show/a1", OWNER, pin("first"))
.await?;
assert_eq!(body["outcome"], "stale", "{body}");
let (_, body) = api
.post("ai/artifacts/show/a1", OWNER, pin("third"))
.await?;
assert_eq!(body["artifact"]["shown_version"], 1, "{body}");
Ok(())
}
@@ -169,7 +191,7 @@ async fn only_a_shared_copy_is_held_to_the_name_limit(db: Pool<Postgres>) -> any
let api = Api::new(&server);
api.publish("draft").await?;
let write = json!({ "base_version": 1, "version": 2, "name": "n".repeat(300), "content": "x" });
let write = json!({ "base_hash": sha256("draft"), "version": 2, "name": "n".repeat(300), "content": "x" });
let (_, body) = api
.post("ai/artifacts/write/never-shared", OWNER, write.clone())
.await?;
+25 -12
View File
@@ -15256,8 +15256,7 @@ paths:
description: >
Makes the artifact an item with a path under the caller's user folder, before its access
list is first changed, with this version as the one people with access see. An artifact
already on the server keeps its path and access list, takes this version when it is newer
than the latest it knows, and leaves the trash.
already on the server keeps its path, access list and versions, and leaves the trash.
operationId: publishAiArtifact
tags:
- ai
@@ -15306,7 +15305,7 @@ paths:
post:
summary: save a new version of one of the caller's shared AI session artifacts
description: >
Refused, with outcome stale, unless base_version is the latest version the server knows.
Refused, with outcome stale, unless base_hash is the SHA-256 of the latest version's text.
People with access see the new version at once unless the owner pinned one.
operationId: writeAiArtifact
tags:
@@ -15321,18 +15320,21 @@ paths:
schema:
type: object
required:
- base_version
- base_hash
- version
- name
- content
properties:
base_version:
type: integer
minimum: 1
description: the version the edit was made on
base_hash:
type: string
description: the SHA-256, in lowercase hex, of the text the edit was made on
version:
type: integer
minimum: 2
minimum: 1
description: >
the number the owner's browser gives the new version; the server stores it
under the next number above its latest instead when this one is not, and
answers with the number it took
name:
type: string
content:
@@ -15367,12 +15369,13 @@ paths:
- version
- name
- content
- base_hash
properties:
pinned:
type: boolean
description: >
true keeps people on this version while newer ones are written; false shows
them the latest version, which version must then be
them the latest version, whose name and content these are
version:
type: integer
minimum: 1
@@ -15380,6 +15383,11 @@ paths:
type: string
content:
type: string
base_hash:
type: string
description: >
the SHA-256, in lowercase hex, of the latest version's text in the owner's
browser; refused, with outcome stale, unless it is the server's latest
responses:
"200":
description: what the change did
@@ -31727,10 +31735,15 @@ components:
type: string
enum: [saved, stale, not_shared]
description: >
stale: the write was based on an older version than latest_version, and nothing was
saved; not_shared: the server holds no live copy of this artifact of the caller's
stale: the change was made on another text than the latest version's, and nothing
was saved; not_shared: the server holds no live copy of this artifact of the caller's
latest_version:
type: integer
description: >
saved: the number the latest version is stored under; stale: the latest version's
latest_hash:
type: string
description: "stale: the SHA-256, in lowercase hex, of the latest version's text"
artifact:
$ref: "#/components/schemas/AiArtifact"
required:
+94 -49
View File
@@ -11,8 +11,9 @@
//! changes who has access).
//!
//! Artifacts live in their owner's browser. A row holds one version, the one people with access
//! see. The owner's browser sends each later version, and a write that was not based on the
//! latest version the row knows is refused, so a stale copy never overwrites a newer one.
//! see. The owner's browser sends each later version, and the row takes it only when it was made
//! on the text of the latest version the row knows, which the row keeps a SHA-256 of: a copy in
//! another of the owner's browsers can carry the same version number over a different text.
use crate::db::{ApiAuthed, DB};
use axum::{
@@ -22,6 +23,7 @@ use axum::{
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use uuid::Uuid;
use windmill_audit::{audit_oss::audit_log, ActionKind};
use windmill_common::{
@@ -184,11 +186,15 @@ struct ArtifactListEntry {
/// error: the caller reads the latest version from it and redoes its edit on top.
#[derive(Serialize)]
struct WriteResult {
/// `saved`, `stale` (based on an older version than `latest_version`), or `not_shared`
/// (the server holds no live copy of this artifact of the caller's).
/// `saved`, `stale` (made on another text than the latest version's), or `not_shared` (the
/// server holds no live copy of this artifact of the caller's).
outcome: &'static str,
/// When saved, the number the latest version is stored under; when stale, the latest's.
#[serde(skip_serializing_if = "Option::is_none")]
latest_version: Option<i32>,
/// When stale, the SHA-256 of the latest version's text.
#[serde(skip_serializing_if = "Option::is_none")]
latest_hash: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
artifact: Option<ArtifactItem>,
}
@@ -198,17 +204,47 @@ impl WriteResult {
WriteResult {
outcome: "saved",
latest_version: Some(row.latest_version),
latest_hash: None,
artifact: Some(ArtifactItem::from_row(row, authed)),
}
}
fn stale(latest_version: i32) -> Self {
WriteResult { outcome: "stale", latest_version: Some(latest_version), artifact: None }
fn stale(latest: Latest) -> Self {
WriteResult {
outcome: "stale",
latest_version: Some(latest.version),
latest_hash: Some(latest.hash),
artifact: None,
}
}
fn not_shared() -> Self {
WriteResult { outcome: "not_shared", latest_version: None, artifact: None }
WriteResult {
outcome: "not_shared",
latest_version: None,
latest_hash: None,
artifact: None,
}
}
/// The answer when a write's conditions matched no row.
fn refused(latest: Option<Latest>) -> Self {
latest.map_or_else(WriteResult::not_shared, WriteResult::stale)
}
}
/// The SHA-256 of a version's text, hex-encoded, as the browser computes it over the same UTF-8.
fn fingerprint(content: &str) -> String {
hex::encode(Sha256::digest(content.as_bytes()))
}
fn check_hash(hash: &str) -> Result<()> {
if hash.len() != 64 || !hash.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
return Err(Error::BadRequest(
"base_hash must be a SHA-256 in lowercase hex".to_string(),
));
}
Ok(())
}
/// Checks an id compared against a `VARCHAR(255)` column: Postgres answers a NUL in a text
@@ -535,10 +571,10 @@ struct PublishArtifact {
}
/// Make one of the caller's artifacts an item, with this version as the one people see, before
/// its access list is first changed. An artifact already on the server keeps its path and
/// access list, and takes this version when it is newer than the latest it knows. One in the
/// trash leaves it with an empty access list: its owner deleted it, so sharing it again starts
/// from nobody, where Restore brings back who it was shared with.
/// its access list is first changed. An artifact already on the server keeps its path, access
/// list and versions: only a write made on its latest version's text replaces that text. One in
/// the trash leaves it with an empty access list: its owner deleted it, so sharing it again
/// starts from nobody, where Restore brings back who it was shared with.
async fn publish_artifact(
authed: ApiAuthed,
Extension(db): Extension<DB>,
@@ -582,12 +618,7 @@ async fn publish_artifact(
sqlx::query_as!(
ArtifactRow,
"UPDATE ai_artifact SET
content = CASE WHEN NOT pinned AND $3 > latest_version THEN $4 ELSE content END,
name = CASE WHEN NOT pinned AND $3 > latest_version THEN $5 ELSE name END,
updated_at = CASE WHEN NOT pinned AND $3 > latest_version THEN now() ELSE updated_at END,
shown_version = CASE WHEN NOT pinned AND $3 > latest_version THEN $3 ELSE shown_version END,
latest_version = GREATEST(latest_version, $3),
session_id = COALESCE(session_id, $6),
session_id = COALESCE(session_id, $3),
extra_perms = CASE WHEN deleted_at IS NULL THEN extra_perms ELSE '{}'::jsonb END,
deleted_at = NULL
WHERE workspace_id = $1 AND artifact_id = $2
@@ -596,9 +627,6 @@ async fn publish_artifact(
deleted_at",
&w_id,
&payload.artifact_id,
payload.version,
&payload.content,
name,
payload.session_id,
)
.fetch_one(&mut *tx)
@@ -626,8 +654,8 @@ async fn publish_artifact(
ArtifactRow,
"INSERT INTO ai_artifact
(workspace_id, artifact_id, path, email, created_by, session_id, name, kind,
role, shown_version, content, latest_version)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $10)
role, shown_version, content, latest_version, latest_hash)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $10, $12)
RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,
role, shown_version, latest_version, pinned, created_at, updated_at,
deleted_at",
@@ -642,6 +670,7 @@ async fn publish_artifact(
payload.role.map(ArtifactRole::as_str),
payload.version,
&payload.content,
fingerprint(&payload.content),
)
.fetch_one(&mut *tx)
.await?;
@@ -664,8 +693,11 @@ async fn publish_artifact(
#[derive(Deserialize)]
struct WriteArtifact {
/// The version the edit was made on; the write is refused unless it is the latest one.
base_version: i32,
/// The SHA-256 of the text the edit was made on; the write is refused unless that is the
/// latest version's text.
base_hash: String,
/// The number the owner's browser gives the new version. Below the next one the server can
/// give, it takes that one instead, and answers with it.
version: i32,
name: String,
content: String,
@@ -682,12 +714,8 @@ async fn write_artifact(
) -> JsonResult<WriteResult> {
let name = payload.name.trim();
check_id("Artifact id", &artifact_id)?;
check_version(payload.base_version)?;
if payload.version <= payload.base_version {
return Err(Error::BadRequest(
"A new version must be above the version it was based on".to_string(),
));
}
check_hash(&payload.base_hash)?;
check_version(payload.version)?;
if let Some(sid) = &payload.session_id {
check_id("Session id", sid)?;
}
@@ -695,7 +723,7 @@ async fn write_artifact(
let mut tx = db.begin().await?;
// Every edit reaches here, shared or not. Only a copy the server keeps is held to its
// bounds: refusing one it has none of would leave its owner unable to edit it at all.
if latest_live_version(&mut tx, &w_id, &artifact_id, &authed.email)
if latest_live(&mut tx, &w_id, &artifact_id, &authed.email)
.await?
.is_none()
{
@@ -703,16 +731,19 @@ async fn write_artifact(
}
check_name(name)?;
check_content(&payload.content)?;
// Numbered above both the latest and the browser's own versions, so neither side ever
// gives two texts one number: the browser stores the edit under the number answered.
let row = sqlx::query_as!(
ArtifactRow,
"UPDATE ai_artifact SET
latest_version = $4,
latest_version = GREATEST(latest_version + 1, $4),
latest_hash = $9,
content = CASE WHEN pinned THEN content ELSE $5 END,
name = CASE WHEN pinned THEN name ELSE $6 END,
shown_version = CASE WHEN pinned THEN shown_version ELSE $4 END,
shown_version = CASE WHEN pinned THEN shown_version ELSE GREATEST(latest_version + 1, $4) END,
updated_at = CASE WHEN pinned THEN updated_at ELSE now() END,
session_id = COALESCE(session_id, $8)
WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND latest_version = $7
WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND latest_hash = $7
AND deleted_at IS NULL
RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,
role, shown_version, latest_version, pinned, created_at, updated_at,
@@ -723,31 +754,38 @@ async fn write_artifact(
payload.version,
&payload.content,
name,
payload.base_version,
&payload.base_hash,
payload.session_id,
fingerprint(&payload.content),
)
.fetch_optional(&mut *tx)
.await?;
let result = match row {
Some(row) => WriteResult::saved(row, &authed),
None => latest_live_version(&mut tx, &w_id, &artifact_id, &authed.email)
.await?
.map_or_else(WriteResult::not_shared, WriteResult::stale),
None => {
WriteResult::refused(latest_live(&mut tx, &w_id, &artifact_id, &authed.email).await?)
}
};
tx.commit().await?;
Ok(Json(result))
}
struct Latest {
version: i32,
hash: String,
}
/// The latest version of one of `email`'s artifacts that is on the server and not in the trash.
async fn latest_live_version(
async fn latest_live(
tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,
w_id: &str,
artifact_id: &str,
email: &str,
) -> Result<Option<i32>> {
Ok(sqlx::query_scalar!(
"SELECT latest_version FROM ai_artifact
) -> Result<Option<Latest>> {
Ok(sqlx::query_as!(
Latest,
"SELECT latest_version AS version, latest_hash AS hash FROM ai_artifact
WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND deleted_at IS NULL",
w_id,
artifact_id,
@@ -760,11 +798,14 @@ async fn latest_live_version(
#[derive(Deserialize)]
struct ShowVersion {
/// True keeps people on `version` while newer ones are written; false shows them the latest,
/// which `version` must then be.
/// whose name and content these are.
pinned: bool,
version: i32,
name: String,
content: String,
/// The SHA-256 of the latest version's text in the owner's browser: the change is refused
/// unless the server's latest version is that text.
base_hash: String,
}
/// Choose the version people with access see.
@@ -779,14 +820,17 @@ async fn show_version(
check_name(name)?;
check_content(&payload.content)?;
check_version(payload.version)?;
check_hash(&payload.base_hash)?;
let mut tx = db.begin().await?;
let row = sqlx::query_as!(
ArtifactRow,
"UPDATE ai_artifact SET
pinned = $4, shown_version = $5, content = $6, name = $7, updated_at = now()
pinned = $4,
shown_version = CASE WHEN $4 THEN $5 ELSE latest_version END,
content = $6, name = $7, updated_at = now()
WHERE workspace_id = $1 AND artifact_id = $2 AND email = $3 AND deleted_at IS NULL
AND CASE WHEN $4 THEN $5 <= latest_version ELSE $5 = latest_version END
AND latest_hash = $8 AND (NOT $4 OR $5 <= latest_version)
RETURNING artifact_id, path, extra_perms, email, created_by, session_id, name, kind,
role, shown_version, latest_version, pinned, created_at, updated_at,
deleted_at",
@@ -797,6 +841,7 @@ async fn show_version(
payload.version,
&payload.content,
name,
&payload.base_hash,
)
.fetch_optional(&mut *tx)
.await?;
@@ -814,14 +859,14 @@ async fn show_version(
ActionKind::Update,
&w_id,
Some(&row.path),
Some([("version", payload.version.to_string().as_str())].into()),
Some([("version", row.shown_version.to_string().as_str())].into()),
)
.await?;
WriteResult::saved(row, &authed)
}
None => latest_live_version(&mut tx, &w_id, &artifact_id, &authed.email)
.await?
.map_or_else(WriteResult::not_shared, WriteResult::stale),
None => {
WriteResult::refused(latest_live(&mut tx, &w_id, &artifact_id, &authed.email).await?)
}
};
tx.commit().await?;
Ok(Json(result))
@@ -82,7 +82,7 @@
}
saving = true
try {
const result = await showVersion(local, workspace, server.latest_version, {
const result = await showVersion(local, workspace, {
pinned,
version,
name: snapshot.name,
@@ -1,10 +1,12 @@
import { get } from 'svelte/store'
import { hash } from '$lib/components/apps/editor/commonAppUtils'
import { AiService, type AiArtifact, type AiArtifactWriteResult } from '$lib/gen'
import { userWorkspaces } from '$lib/stores'
import { scopedKey } from '$lib/userScopedStorage'
import {
currentVersion,
deleteArtifact,
getArtifactVersion,
patchArtifact,
purgeDeletedArtifacts,
TRASH_RETENTION_MS,
@@ -17,6 +19,45 @@ export function homeWorkspace(workspaceId: string): string {
return shareWorkspaceId(workspaceId, get(userWorkspaces))
}
/** The SHA-256 of a version's text, which the server knows its latest version by: two of the
* owner's browsers can each hold a different text under one version number. */
export function fingerprint(content: string): Promise<string> {
return hash(content)
}
/** Whether this browser holds `version` of `local`, older than its latest, with the text whose
* SHA-256 is `latestHash`: the server's latest version is then one this browser wrote on the way
* to its own latest, which was made on it. */
export async function holdsOlder(
local: PersistedArtifact,
version: number,
latestHash: string
): Promise<boolean> {
if (version >= currentVersion(local)) return false
const held = await getArtifactVersion(local.id, version).catch(() => undefined)
return held !== undefined && (await fingerprint(held.content)) === latestHash
}
/** Give a server copy whose latest version `holdsOlder` found in this browser this browser's
* latest, as a write made on that version. Refused if the server's latest moved meanwhile. */
function bringUpToDate(
local: PersistedArtifact,
workspace: string,
latestHash: string
): Promise<AiArtifactWriteResult> {
return AiService.writeAiArtifact({
workspace,
artifactId: local.id,
requestBody: {
base_hash: latestHash,
version: currentVersion(local),
name: local.name,
content: local.content,
session_id: local.sessionId
}
})
}
/** A call about one of the user's artifacts on the server; undefined when the server holds no
* copy of it, which is every artifact never shared. */
async function onServer<T>(call: () => Promise<T>): Promise<T | undefined> {
@@ -30,9 +71,13 @@ async function onServer<T>(call: () => Promise<T>): Promise<T | undefined> {
/** Put the artifact on the server as its owner's item, with the version this browser holds as
* the one people see, before its access list is first changed. A copy already there keeps its
* path and access list. */
export function publishArtifact(a: PersistedArtifact, workspace: string): Promise<AiArtifact> {
return AiService.publishAiArtifact({
* path and access list, and takes this browser's latest only when its own latest is one of this
* browser's older versions. */
export async function publishArtifact(
a: PersistedArtifact,
workspace: string
): Promise<AiArtifact> {
const item = await AiService.publishAiArtifact({
workspace,
requestBody: {
artifact_id: a.id,
@@ -44,19 +89,42 @@ export function publishArtifact(a: PersistedArtifact, workspace: string): Promis
content: a.content
}
})
if (item.latest_version >= currentVersion(a)) return item
// Only the server knows its latest text's SHA-256, so the write names this browser's text
// under the same number, and the server refuses it when that is not its latest.
const held = await getArtifactVersion(a.id, item.latest_version).catch(() => undefined)
if (!held) return item
try {
const result = await bringUpToDate(a, workspace, await fingerprint(held.content))
return result.artifact ?? item
} catch {
return item
}
}
/** Choose the version people with access see: `pinned` keeps them on `version` while newer ones
* are written, unpinned shows them the latest, which `version` must then be. The server takes
* only versions it knows, so a later one this browser holds goes to it first. */
* are written, unpinned shows them the latest, which `local` holds. Refused, `stale`, unless the
* server's latest version is `local`'s; a server copy behind `local` is brought up to it first. */
export async function showVersion(
local: PersistedArtifact,
workspace: string,
serverLatest: number,
shown: { pinned: boolean; version: number; name: string; content: string }
): Promise<AiArtifactWriteResult> {
if (serverLatest < currentVersion(local)) await publishArtifact(local, workspace)
return AiService.showAiArtifactVersion({ workspace, artifactId: local.id, requestBody: shown })
const base_hash = await fingerprint(local.content)
const show = () =>
AiService.showAiArtifactVersion({
workspace,
artifactId: local.id,
requestBody: { ...shown, base_hash }
})
const result = await show()
const { latest_version, latest_hash } = result
if (result.outcome !== 'stale' || latest_version === undefined || latest_hash === undefined) {
return result
}
if (!(await holdsOlder(local, latest_version, latest_hash))) return result
const caught = await bringUpToDate(local, workspace, latest_hash)
return caught.outcome === 'saved' ? show() : caught
}
/** Move one of the user's artifacts to Recently deleted. Sharing stops while it is there. */
@@ -16,7 +16,13 @@ import {
type ArtifactVersion,
type PersistedArtifact
} from './artifactsDB'
import { homeWorkspace, publishArtifact, restoreArtifact, trashArtifact } from './artifactLibrary'
import {
fingerprint,
holdsOlder,
homeWorkspace,
restoreArtifact,
trashArtifact
} from './artifactLibrary'
export interface CreateArtifactInput {
name: string
@@ -69,19 +75,20 @@ export class ArtifactPersistenceError extends Error {
}
}
/** A new version of an artifact, not stored because a later one exists: one its owner wrote
* from another browser since this one last did, against which the server refused it, or one
* another tab stored after this edit was made. */
/** A new version of an artifact, not stored because it was made on a version that is no longer
* the latest: the server's latest is one its owner wrote from another browser, against which
* the server refused it, or another tab stored a later one after this edit was made. */
export class ArtifactStaleError extends Error {
constructor(
readonly artifact: PersistedArtifact,
/** The latest version: the server's, or the one another tab stored. */
/** The latest version: the number this browser holds it under when `caughtUp`, the
* server's otherwise. */
readonly latest: number,
/** Whether this browser now holds that version, for the edit to be redone on it. */
readonly caughtUp: boolean,
/** The version the server took the edit as, before another tab stored a later one. That
* one was made on it, since the server takes no write made on an older version, so the
* edit is already in it and redoing it would apply it twice. */
* one was made on it, since the server takes no write made on another version's text, so
* the edit is already in it and redoing it would apply it twice. */
readonly savedAs?: number
) {
super(`Artifact ${artifact.id} changed in another tab or browser (now v${latest})`)
@@ -89,6 +96,9 @@ export class ArtifactStaleError extends Error {
}
}
/** What the server did with an edit: took it as version `version`, or holds no copy of it. */
type Sent = { outcome: 'saved'; version: number } | { outcome: 'unshared' }
/**
* Reactive view of the active session's artifacts, owned by AIChatManager (like
* AttachedFilesStore). The consumer drives which session is loaded via setSession(); the
@@ -252,6 +262,7 @@ export class SessionArtifactsStore {
})
: undefined
const base = prior ? currentVersion(prior) : 0
const savedAs = sent?.outcome === 'saved' ? sent.version : undefined
let refused = false
let overtaken: PersistedArtifact | undefined
const { outcome, artifact } = await mutateArtifact(id, (stored) => {
@@ -274,25 +285,21 @@ export class SessionArtifactsStore {
) {
throw new PlanWriteRefusedError()
}
// Made on `prior`, and weighed by the server against it if it was asked at all, which
// an edit leaving `prior`'s text as it is never is. Over a row that moved past `prior`,
// it would land under a number the server never checked, the base of this browser's
// next write. Two tabs' edits of an artifact the server has no copy of both land.
if (prior && sent !== 'unshared' && currentVersion(existing) > base) {
// Made on `prior`, whether or not the server was asked, which it never is for an edit
// leaving `prior`'s text as it is. Over a row another tab moved past `prior`, it would
// replace that tab's version unseen, and with it one the tab shared since.
if (prior && currentVersion(existing) > base) {
overtaken = existing
return undefined
}
const edit = reviseInto(existing, input)
const edit = reviseInto(existing, input, savedAs)
edit.artifact.workspaceId ??= this.#home()
return edit
})
if (refused) return undefined
if (overtaken) this.#overtaken(overtaken, sent === 'saved' ? base + 1 : undefined)
if (overtaken) this.#overtaken(overtaken, savedAs)
if (artifact?.role === 'plan' && outcome !== 'saved') throw new ArtifactPersistenceError()
if (artifact) {
this.#reflect(artifact)
if (sent === 'behind') this.#bringServerUpToDate(artifact)
}
if (artifact) this.#reflect(artifact)
return artifact
}
@@ -306,106 +313,135 @@ export class SessionArtifactsStore {
/**
* Hand the next version of an artifact to the server before this browser stores it: when the
* artifact is shared, people with access see it there. The server refuses a version based on
* an older one than the latest it knows, which its owner wrote from another browser since
* this one last did; that throws ArtifactStaleError, and a call that fails throws its error.
* Resolves `saved` when the server took the version, `unshared` when it holds no copy to take
* it into, and `behind` when its copy is older than this browser's, for the caller to bring up
* to date once the version is stored.
* artifact is shared, people with access see it there. The server takes only an edit made on
* the text of its latest version; one made on another throws ArtifactStaleError once this
* browser has caught up where it can, and a call that fails throws its error. Resolves
* `saved` with the number the server gave the version, or `unshared` when it holds no copy
* to take it into.
*/
async #sendToServer(
prior: PersistedArtifact,
next: { name: string; content: string }
): Promise<'saved' | 'unshared' | 'behind'> {
): Promise<Sent> {
const workspace = prior.workspaceId ?? this.#home()
if (!workspace) return 'unshared'
const base = currentVersion(prior)
// Not caught: a version stored here that the server never weighed is the base of this
// browser's next write, which would then replace one written elsewhere in between.
const result: AiArtifactWriteResult = await AiService.writeAiArtifact({
workspace,
artifactId: prior.id,
requestBody: {
base_version: base,
version: base + 1,
name: next.name,
content: next.content,
session_id: prior.sessionId
}
})
if (result.outcome === 'saved') return 'saved'
const latest = result.latest_version
if (result.outcome !== 'stale' || latest === undefined) return 'unshared'
if (latest < base) return 'behind'
throw new ArtifactStaleError(
prior,
latest,
await this.#takeServerCopy(prior, workspace, latest)
)
if (!workspace) return { outcome: 'unshared' }
const write = (baseHash: string): Promise<AiArtifactWriteResult> =>
AiService.writeAiArtifact({
workspace,
artifactId: prior.id,
requestBody: {
base_hash: baseHash,
version: currentVersion(prior) + 1,
name: next.name,
content: next.content,
session_id: prior.sessionId
}
})
// Not caught: a version stored here that the server never weighed would be the text of
// this browser's next write, which would then replace one written elsewhere in between.
let result = await write(await fingerprint(prior.content))
let { latest_version: latest, latest_hash: latestHash } = result
// A server copy that holds an older version of this browser's, which a version stored
// while it had no copy went past: the edit is made on that version's successors.
if (
result.outcome === 'stale' &&
latest !== undefined &&
latestHash !== undefined &&
(await holdsOlder(prior, latest, latestHash))
) {
result = await write(latestHash)
;({ latest_version: latest, latest_hash: latestHash } = result)
}
if (result.outcome === 'saved') {
return { outcome: 'saved', version: latest ?? currentVersion(prior) + 1 }
}
if (result.outcome !== 'stale' || latest === undefined) return { outcome: 'unshared' }
throw await this.#refused(prior, workspace, latest, latestHash)
}
/**
* Catch this browser up with version `latest`, the server's latest: from the store, where
* another tab may have put it, or else from the server's copy when that holds it. The server
* keeps only the version people see, an older one while its owner has one pinned. Resolves
* whether this browser now holds version `latest`.
* The error for an edit the server refused, once this browser has caught up with the server's
* latest version where it can: from the store, where another tab may have put it, or else from
* the server's copy. That holds only the version people see, an older one while its owner has
* one pinned.
*/
async #takeServerCopy(
async #refused(
prior: PersistedArtifact,
workspace: string,
latest: number
): Promise<boolean> {
if (await this.#holds(prior.id, latest)) return true
latest: number,
latestHash: string | undefined
): Promise<ArtifactStaleError> {
const held = (await this.#latestHeld(prior.id)) ?? prior
if (latestHash !== undefined && (await fingerprint(held.content)) === latestHash) {
return new ArtifactStaleError(held, currentVersion(held), true)
}
let copy: AiArtifactWithContent
try {
copy = await AiService.getAiArtifact({ workspace, artifactId: prior.id })
} catch {
return false
return new ArtifactStaleError(held, latest, false)
}
if (copy.shown_version !== latest) return false
await this.#adopt(prior.id, copy)
return this.#holds(prior.id, latest)
if (copy.shown_version !== copy.latest_version)
return new ArtifactStaleError(held, latest, false)
const caught = (await this.#adopt(held, copy, workspace)) ?? held
const redo = caught.content === copy.content || currentVersion(caught) > currentVersion(held)
return new ArtifactStaleError(caught, redo ? currentVersion(caught) : latest, redo)
}
/** Whether the copy an edit is redone on, the one `get` reads, holds `version` or a later one,
* once this list has taken the stored row if that is further along. */
async #holds(id: string, version: number): Promise<boolean> {
/** The copy an edit is redone on, the one `get` reads, once this list has taken the stored row
* if that is further along. */
async #latestHeld(id: string): Promise<PersistedArtifact | undefined> {
const stored = await getArtifact(id).catch(() => undefined)
const held = furtherAlong(
stored,
this.artifacts.find((a) => a.id === id)
)
if (!held || !isLive(held)) return false
if (!held || !isLive(held)) return undefined
this.#reflect(held)
return currentVersion(held) >= version
return held
}
/**
* This browser's copy of an artifact, caught up with a newer version its owner wrote in
* another browser when `copy`, the server's, holds it: unless an older one is pinned there.
* This browser's copy of an artifact, caught up with the server's latest version when another
* of its owner's browsers wrote it: unless an older one is pinned, which keeps the latest's
* text off the server, or the server's latest is one of this browser's older versions.
*/
async catchUp(local: PersistedArtifact, copy: AiArtifactWithContent): Promise<PersistedArtifact> {
if (
!isLive(local) ||
copy.shown_version !== copy.latest_version ||
copy.shown_version <= currentVersion(local)
copy.content === local.content ||
(await holdsOlder(local, copy.latest_version, await fingerprint(copy.content)))
) {
return local
}
return (await this.#adopt(local.id, copy)) ?? local
return (await this.#adopt(local, copy, local.workspaceId ?? this.#home())) ?? local
}
/**
* This browser's copy of an artifact once it holds `copy`'s version, the server's. When the
* store already holds that version or a later one, which another tab of this browser took,
* that copy is the one reflected: the in-memory list can be older than the store.
* This browser's copy of an artifact once it holds `copy`, the server's latest version, as the
* version after `local`'s, under the server's number when that is higher. Nothing is adopted
* when the store moved past `local`, which another tab did, or holds that text already: the
* stored row is the one reflected then, as the in-memory list can be older than the store.
*/
async #adopt(id: string, copy: AiArtifactWithContent): Promise<PersistedArtifact | undefined> {
const version = copy.shown_version
async #adopt(
local: PersistedArtifact,
copy: AiArtifactWithContent,
workspace: string | undefined
): Promise<PersistedArtifact | undefined> {
const base = currentVersion(local)
const version = Math.max(copy.latest_version, base + 1)
let stored: PersistedArtifact | undefined
const write = await mutateArtifact(id, (existing) => {
const write = await mutateArtifact(local.id, (existing) => {
stored = existing
if (!existing || currentVersion(existing) >= version) return undefined
if (
!existing ||
!isLive(existing) ||
currentVersion(existing) !== base ||
existing.content === copy.content
) {
return undefined
}
const next: PersistedArtifact = {
...existing,
name: copy.name,
@@ -418,30 +454,39 @@ export class SessionArtifactsStore {
snapshots: [snapshotOf(next, version, 'Written in another browser')]
}
})
// Above the server's number, this browser's own versions took it: the server's copy takes
// this one, so that a version has one number in every browser, which pinning names it by.
if (write.artifact && workspace && version > copy.latest_version) {
try {
await AiService.writeAiArtifact({
workspace,
artifactId: local.id,
requestBody: {
base_hash: await fingerprint(copy.content),
version,
name: copy.name,
content: copy.content,
session_id: local.sessionId
}
})
} catch (err) {
console.error('Could not number the server copy of the artifact', err)
}
}
const held = furtherAlong(
write.artifact ?? stored,
this.artifacts.find((a) => a.id === id)
this.artifacts.find((a) => a.id === local.id)
)
if (held && isLive(held)) this.#reflect(held)
return held
}
/** Give the server a version this browser stored without it, which its owner's writes from
* here are refused until it has. */
#bringServerUpToDate(artifact: PersistedArtifact): void {
const workspace = artifact.workspaceId ?? this.#home()
if (!workspace) return
publishArtifact(artifact, workspace).catch((err) =>
console.error('Could not bring the server copy of the artifact up to date', err)
)
}
/**
* Put a proposal into the session's one plan document, creating it the first time.
*
* Both halves inside one transaction, so a second tab proposing at the same moment revises
* the row this one wrote rather than racing it: the id is the session's, and whichever
* transaction runs second reads the first one's result.
* Both halves inside one transaction, so a second tab proposing at the same moment cannot
* race this one: the id is the session's, and whichever transaction runs second reads the
* first one's result.
*/
async savePlan(
sessionId: string,
@@ -455,16 +500,17 @@ export class SessionArtifactsStore {
? await this.#sendToServer(prior, revision)
: undefined
const base = prior ? currentVersion(prior) : 0
const savedAs = sent?.outcome === 'saved' ? sent.version : undefined
let overtaken: PersistedArtifact | undefined
const { outcome, artifact } = await mutateArtifact(id, (existing) => {
// As in `update`. Without `prior` no plan was there to make this one on, and it
// revises whatever another tab put in the slot meanwhile.
if (prior && sent !== 'unshared' && existing && currentVersion(existing) > base) {
if (prior && existing && currentVersion(existing) > base) {
overtaken = existing
return undefined
}
if (existing) {
const edit = reviseInto(isLive(existing) ? existing : revived(existing), revision)
const edit = reviseInto(isLive(existing) ? existing : revived(existing), revision, savedAs)
edit.artifact.workspaceId ??= this.#home()
return edit
}
@@ -484,11 +530,10 @@ export class SessionArtifactsStore {
}
return { artifact: created, snapshots: [snapshotOf(created, 1)] }
})
if (overtaken) this.#overtaken(overtaken, sent === 'saved' ? base + 1 : undefined)
if (overtaken) this.#overtaken(overtaken, savedAs)
// A plan the database refused would let the user approve one that disappears on reload.
if (!artifact || outcome !== 'saved') throw new ArtifactPersistenceError()
this.#reflect(artifact)
if (sent === 'behind') this.#bringServerUpToDate(artifact)
return artifact
}
@@ -623,11 +668,18 @@ function furtherAlong(
* writer so the version and approval rules cannot drift between them; always given the row
* `furtherAlong` settled on, never a remembered one.
*/
function reviseInto(existing: PersistedArtifact, input: UpdateArtifactInput): ArtifactEdit {
function reviseInto(
existing: PersistedArtifact,
input: UpdateArtifactInput,
/** The number the server gave this version, when it took it. */
savedAs?: number
): ArtifactEdit {
// Only a content change earns a version: a rename or an identical rewrite would otherwise
// fill the picker with entries the user cannot tell apart.
const contentChanged = input.content !== undefined && input.content !== existing.content
const version = currentVersion(existing) + (contentChanged ? 1 : 0)
const version = contentChanged
? (savedAs ?? currentVersion(existing) + 1)
: currentVersion(existing)
// Carried onto a version this write produced, so one that produces none moves nothing: a
// rename would otherwise promote a proposal the user turned down.
const approvedVersion =
@@ -1,3 +1,4 @@
import { createHash } from 'node:crypto'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { IDBFactory } from 'fake-indexeddb'
import { planFirst, SessionArtifactsStore } from './artifactsState.svelte'
@@ -155,21 +156,23 @@ describe('SessionArtifactsStore', () => {
expect(await store.update('nope', { content: 'x' })).toBeUndefined()
})
it('gives two tabs editing at once distinct versions, keeping both snapshots', async () => {
// Without the transactional read both tabs stamp the same next version, and one edit
// and its snapshot vanish under the other.
it('stores only the first of two edits two tabs make at once on one version', async () => {
// The second, stored over the first, would replace a version it never saw, and with it
// one the other tab may have shared since.
const other = new (await import('./artifactsState.svelte')).SessionArtifactsStore()
await store.setSession('s1')
const created = await store.create('s1', { name: 'Doc', content: 'v1' })
await other.setSession('s1')
await Promise.all([
const results = await Promise.allSettled([
store.update(created.id, { content: 'from A', note: 'A' }),
other.update(created.id, { content: 'from B', note: 'B' })
])
expect((await dbMod.listArtifactVersions(created.id)).map((v) => v.version)).toEqual([3, 2, 1])
expect((await dbMod.getArtifact(created.id))?.version).toBe(3)
expect(results.filter((r) => r.status === 'rejected')).toMatchObject([
{ reason: { name: 'ArtifactStaleError', latest: 2, caughtUp: true } }
])
expect((await dbMod.listArtifactVersions(created.id)).map((v) => v.version)).toEqual([2, 1])
})
it('keeps an edit the store refused when the next update lands', async () => {
@@ -404,21 +407,23 @@ describe('SessionArtifactsStore', () => {
expect(store.artifacts.map((a) => a.id)).toContain(plan.id)
})
it('gives two tabs proposing at once distinct versions, keeping both snapshots', async () => {
it('stores only the first of two proposals two tabs make at once on one plan', async () => {
// The hazard the transaction exists for: read outside it and both tabs stamp the same
// next version, so one proposal and its snapshot vanish under the other.
const other = new (await import('./artifactsState.svelte')).SessionArtifactsStore()
await store.setSession('s1')
await store.savePlan('s1', { name: 'Plan', content: 'v1', note: 'first' }, undefined)
await Promise.all([
const results = await Promise.allSettled([
store.savePlan('s1', { name: 'Plan', content: 'from A', note: 'A' }, undefined),
other.savePlan('s1', { name: 'Plan', content: 'from B', note: 'B' }, undefined)
])
expect(results.filter((r) => r.status === 'rejected')).toMatchObject([
{ reason: { name: 'ArtifactStaleError', latest: 2 } }
])
const versions = (await store.listVersions(dbMod.planArtifactId('s1'))).map((v) => v.version)
expect(versions).toEqual([3, 2, 1])
expect((await dbMod.getArtifact(dbMod.planArtifactId('s1')))?.version).toBe(3)
expect(versions).toEqual([2, 1])
})
it('an approval racing a newer proposal moves the pointer without reverting content', async () => {
@@ -553,9 +558,14 @@ describe('SessionArtifactsStore with a server copy', () => {
it('refuses an edit the owner overtook from another browser, and takes that version', async () => {
const { AiService, shared, doc } = await sharedDoc()
AiService.writeAiArtifact.mockResolvedValue({ outcome: 'stale', latest_version: 3 })
AiService.writeAiArtifact.mockResolvedValue({
outcome: 'stale',
latest_version: 3,
latest_hash: sha256('v3 from elsewhere')
})
AiService.getAiArtifact.mockResolvedValue({
shown_version: 3,
latest_version: 3,
name: 'Doc',
content: 'v3 from elsewhere'
} as never)
@@ -567,15 +577,53 @@ describe('SessionArtifactsStore with a server copy', () => {
})
expect(await shared.get(doc.id)).toMatchObject({ version: 3, content: 'v3 from elsewhere' })
// The edit is redone on that version, and lands.
AiService.writeAiArtifact.mockResolvedValue({ outcome: 'saved' } as never)
AiService.writeAiArtifact.mockResolvedValue({ outcome: 'saved', latest_version: 4 })
expect(await shared.update(doc.id, { content: 'v4 from here' })).toMatchObject({ version: 4 })
expect(AiService.writeAiArtifact).toHaveBeenLastCalledWith(
expect.objectContaining({
requestBody: expect.objectContaining({ base_version: 3, version: 4 })
requestBody: expect.objectContaining({ base_hash: sha256('v3 from elsewhere'), version: 4 })
})
)
})
it('refuses an edit made on another text than the server holds under that number', async () => {
// Another of the owner's browsers wrote its own v1 and shared it: the numbers match, and
// the edit must still not replace what people see.
const { AiService, shared, doc } = await sharedDoc()
const theirs = { name: 'Doc', content: 'v1 elsewhere', shown_version: 1, latest_version: 1 }
AiService.writeAiArtifact.mockResolvedValueOnce({
outcome: 'stale',
latest_version: 1,
latest_hash: sha256('v1 elsewhere')
})
AiService.getAiArtifact.mockResolvedValue(theirs as never)
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'saved', latest_version: 2 })
await expect(shared.update(doc.id, { content: 'v2 from here' })).rejects.toMatchObject({
name: 'ArtifactStaleError',
latest: 2,
caughtUp: true
})
expect(await shared.get(doc.id)).toMatchObject({ version: 2, content: 'v1 elsewhere' })
// The server's copy takes the number this browser gave that text.
expect(AiService.writeAiArtifact).toHaveBeenLastCalledWith(
expect.objectContaining({
requestBody: expect.objectContaining({
base_hash: sha256('v1 elsewhere'),
version: 2,
content: 'v1 elsewhere'
})
})
)
})
it('stores a version under the number the server gave it', async () => {
const { AiService, shared, doc } = await sharedDoc()
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'saved', latest_version: 5 })
expect(await shared.update(doc.id, { content: 'v2' })).toMatchObject({ version: 5 })
expect(await shared.getVersion(doc.id, 5)).toMatchObject({ content: 'v2' })
})
it('catches up with a version written in another browser, unless an older one is pinned', async () => {
const { shared, doc } = await sharedDoc()
const copy = { name: 'Doc', content: 'v3 from elsewhere', latest_version: 3 }
@@ -591,7 +639,11 @@ describe('SessionArtifactsStore with a server copy', () => {
const { AiService, shared, doc } = await sharedDoc()
const copy = { name: 'Doc', content: 'v3 from elsewhere', shown_version: 3, latest_version: 3 }
await new stateMod.SessionArtifactsStore(() => 'ws').catchUp(doc, copy as never)
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'stale', latest_version: 3 })
AiService.writeAiArtifact.mockResolvedValueOnce({
outcome: 'stale',
latest_version: 3,
latest_hash: sha256('v3 from elsewhere')
})
AiService.getAiArtifact.mockResolvedValue(copy as never)
await expect(shared.update(doc.id, { content: 'v2 from here' })).rejects.toMatchObject({
@@ -605,7 +657,11 @@ describe('SessionArtifactsStore with a server copy', () => {
const { AiService, shared, doc } = await sharedDoc()
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'saved' } as never)
await new stateMod.SessionArtifactsStore(() => 'ws').update(doc.id, { content: 'v2 elsewhere' })
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'stale', latest_version: 2 })
AiService.writeAiArtifact.mockResolvedValueOnce({
outcome: 'stale',
latest_version: 2,
latest_hash: sha256('v2 elsewhere')
})
AiService.getAiArtifact.mockResolvedValue({
name: 'Doc',
content: 'v1',
@@ -667,24 +723,31 @@ describe('SessionArtifactsStore with a server copy', () => {
expect(await shared.get(doc.id)).toMatchObject({ version: 1, content: 'v1' })
})
it('brings a server copy behind this browser up to date', async () => {
it('writes an edit over a server copy that holds one of its older versions', async () => {
const { AiService, shared, doc } = await sharedDoc()
// Shared before its writes reached the server, which still holds the version shared then.
// Stored while the server held no copy, so the copy shared since holds v1.
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'not_shared' })
await shared.update(doc.id, { content: 'v2' })
AiService.writeAiArtifact.mockResolvedValueOnce({
outcome: 'stale',
latest_version: 1,
latest_hash: sha256('v1')
})
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'saved', latest_version: 3 })
AiService.writeAiArtifact.mockResolvedValueOnce({ outcome: 'stale', latest_version: 1 })
AiService.publishAiArtifact.mockResolvedValue({} as never)
expect(await shared.update(doc.id, { content: 'v3' })).toMatchObject({ version: 3 })
expect(AiService.publishAiArtifact).toHaveBeenCalledWith(
expect(AiService.writeAiArtifact).toHaveBeenLastCalledWith(
expect.objectContaining({
workspace: 'ws',
requestBody: expect.objectContaining({ artifact_id: doc.id, version: 3, content: 'v3' })
requestBody: expect.objectContaining({ base_hash: sha256('v1'), version: 3, content: 'v3' })
})
)
})
})
function sha256(text: string): string {
return createHash('sha256').update(text, 'utf8').digest('hex')
}
function mk(over: Partial<db.PersistedArtifact> = {}): db.PersistedArtifact {
return {
id: 'a1',
@@ -339,7 +339,7 @@
const artifact = liveLocal
if (!artifact || !server || !workspace) return
return run(async () => {
const result = await showVersion(artifact, workspace, server.latest_version, {
const result = await showVersion(artifact, workspace, {
pinned: false,
version: currentVersion(artifact),
name: artifact.name,