Compare commits

..

11 Commits

Author SHA1 Message Date
BFlat 8227e33a97 Fix tiny icon on the 3D stage create-from-image button 2026-09-28 12:17:33 +07:00
BFlat f41a2b2564 Fix icon sizing, menu colors, and prompt box toggle alignment
- Safelist the lucide class so the icon sizing rule is no longer purged
  and icons scale with their text instead of rendering at 24px
- Use the webapp home colors for the apps page and apps menu tiles, and
  the webapp badge style on the apps page
- Match the top menu active and hover states to the webapp nav, and
  shrink its tooltips to plain 12px text
- Align toggle buttons (Instrumental, sound, etc.) and @Characters with
  the popover triggers beside them
2026-09-28 12:14:41 +07:00
BFlat ba4be8aa6b Match desktop app styling to the webapp
Bring the desktop app's UI in line with the webapp's brutalist design:
flat near-black surfaces, white/15 hairline borders, square panels and
modals, 3px corners on controls, white primary buttons, mono uppercase
labels, and Archivo display headings.

- Retoken the default theme, fonts, and global CSS to the webapp values
- Port the webapp's restyled shared components (buttons, modals,
  popovers, tooltips, inputs, select, switch, model selector)
- Restyle prompt boxes, galleries, lightbox, and the 3D scene editor
- Render the webapp pricing table inside the desktop pricing modal
  (new @storyteller/ui-pricing-table package), keeping the Tauri
  purchase and plan-management flow
- Restyle settings, login, credits, and provider modals
- Restyle the top bar, task queue, create pages, and apps page
2026-09-28 11:54:04 +07:00
Brandon Thomas 93b664d871
client identity (origin, user agent) (#1962) 2026-09-27 23:41:15 -04:00
Brandon Thomas 92e6f438c3
better dev script (#1961) 2026-09-27 14:48:34 -04:00
Brandon Thomas df707bf8e1
performance changes (#1959) 2026-09-26 17:50:36 -07:00
Brandon Thomas 780e4494e9
fix login video on desktop (#1958) 2026-09-26 17:08:31 -07:00
Brandon Thomas c3844acdad
ArtCraft 0.41 (#1957)
- website-based login
2026-09-26 03:43:28 -07:00
Brandon Thomas 8456e2fd06
website based login challenges (#1956) 2026-09-26 03:42:09 -07:00
Brandon Thomas 95f8f659a5
ArtCraft 0.40.0 (#1955) 2026-09-18 16:26:35 -04:00
Brandon Thomas 3c5038c159
Added new models and modes: GPT Image 2.5, Wan, Output Formats (#1954) 2026-09-18 16:23:44 -04:00
267 changed files with 8385 additions and 2555 deletions

View File

@ -44,6 +44,7 @@ explicitly authorizes a cache cleanup.
- Prefer `use` imports over inline fully-qualified paths; only qualify inline for true one-offs or std collisions
- TypeScript with Nx, React, Vite, Zustand, and Three.js
- Use two spaces for indentation
- Each Tauri command belongs in its own file module, named after the command. Keep shared state, types, and helpers in separate support modules; see the [Storyteller command conventions](crates/desktop/artcraft/src/services/storyteller/commands/AGENTS.md).
### File Layout

9
Cargo.lock generated
View File

@ -262,6 +262,7 @@ version = "0.0.1"
dependencies = [
"anyhow",
"artcraft_api_defs",
"artcraft_client_identity",
"backoff",
"chrono",
"cloudflare_errors",
@ -282,6 +283,13 @@ dependencies = [
"uuid_utils",
]
[[package]]
name = "artcraft_client_identity"
version = "0.0.1"
dependencies = [
"url",
]
[[package]]
name = "artcraft_router"
version = "0.0.1"
@ -7018,6 +7026,7 @@ dependencies = [
name = "tauri-plugin-http"
version = "2.4.3"
dependencies = [
"artcraft_client_identity",
"bytes",
"cookie_store 0.21.1",
"data-url",

View File

@ -16,6 +16,7 @@ members = [
"crates/api_clients/worldlabs_api_client",
"crates/api_clients/worldlabs_consumer_client",
"crates/desktop/artcraft",
"crates/lib/artcraft_client_identity",
"crates/lib/browser_emulation",
"crates/lib/build_metadata",
"crates/lib/caching/memory_store",
@ -49,6 +50,7 @@ publish = false
[workspace.dependencies]
artcraft_api_defs = { path = "crates/api_clients/artcraft/artcraft_api_defs" }
artcraft_client = { path = "crates/api_clients/artcraft/artcraft_client" }
artcraft_client_identity = { path = "crates/lib/artcraft_client_identity" }
artcraft_router = { path = "crates/api_clients/artcraft/artcraft_router" }
browser_emulation = { path = "crates/lib/browser_emulation" }
cookie_store_wrapper = { path = "crates/lib/cookie_store_wrapper" }

View File

@ -9,21 +9,67 @@ To set up the ArtCraft development environment, install the following:
1. [Install Rust](https://doc.rust-lang.org/cargo/getting-started/installation.html).
2. [Install npm](https://nodejs.org/en/download) or [nvm](https://github.com/nvm-sh/nvm). (Node version `v24.13.0` works at time of writing.)
3. [Install nx](https://nx.dev/docs/getting-started/installation). (Nx version `v22.4.5` works at time of writing.)
3. The frontend's Nx and Vite dependencies are installed locally with npm; a global Nx installation is not required for the combined Unix launcher.
4. [Install Tauri CLI](https://v2.tauri.app/reference/cli/). (Version `tauri-cli 2.10.0` works at time of writing.)
An easy way to get started with running the app in development is to run the two commands (in separate terminals):
**Mac and Linux Development**
```bash
# Run the frontend dev server
./script/artcraft/unix_frontend_dev.sh
# Start the frontend and Rust/Tauri together in one terminal
./script/artcraft/unix_dev.sh
# Run the Tauri Rust application
./script/artcraft/unix_rust_dev.sh
# Optionally start the free-port search at another port
ARTCRAFT_DEV_PORT=6200 ./script/artcraft/unix_dev.sh
```
Use the combined launcher instead of starting the two legacy dev scripts. It
works from any working directory when invoked by its path and installs frontend
dependencies if the local Vite installation is missing. Node.js 20+ is required.
The launcher binds Vite to `127.0.0.1`, starting at port **5193** and trying
successive ports until one is available. It leaves existing listeners alone.
Only after the real frontend socket is bound does it start Tauri with that exact
`devUrl`. HTTP and the HMR websocket share the selected port; Rust communicates
through native Tauri IPC and needs no separate HTTP port. Configuration overrides
are passed in memory, without changing the checked-in Tauri config.
The native HTTP bridge normalizes loopback development origins for first-party
API requests so an automatically selected port does not break login or media
loading. See the [desktop session regression checks](../docs/desktop-session-regression.md)
when changing ports, the launcher, or authentication.
JavaScript, TypeScript, React, and CSS changes use Vite hot reload; compatible
React component edits use Fast Refresh. Changes that cannot be hot-replaced
reload the page. Rust changes use `cargo tauri dev`'s automatic **rebuild and app
restart**, including dependent workspace crates. SQLx metadata and SQLite
migrations are also watched. Rust reload is a process restart, so it does not
preserve unsaved in-memory app state. See [Tauri's watch behavior](https://v2.tauri.app/develop/#reacting-to-source-code-changes).
After startup, a Vite configuration restart must reuse the chosen port or report
an error; it cannot silently switch to another port while Tauri uses an old URL.
Ctrl-C stops this session's frontend, Rust watcher/compiler, and desktop app.
If the Rust watcher exits, the launcher closes Vite and propagates the exit code.
It never finds or terminates another app by name or port.
The launcher retains the existing Unix defaults for `VITE_ENVIRONMENT_TYPE`,
`SQLX_OFFLINE`, `RUSTFLAGS`, and the Linux WebKit workarounds. Explicit environment
overrides are preserved. It uses the normal Artcraft app data and Cargo target
directory; port separation does not create an isolated account/data profile, and
concurrent Rust builds can wait on Cargo's build lock.
To verify the launcher without compiling Rust or opening a desktop window:
```bash
node --test frontend/scripts/unix-dev.test.mjs
```
The tests use real Vite listeners and HMR, with a test-owned fake Cargo process
tree. They cover occupied ports, simultaneous launches, React edits, shutdown,
Rust-process failure, and watcher arguments. To verify native Rust reload, run
the launcher, wait for the desktop window, make a Rust source edit, and check for
a rebuild/restart in the same terminal. Frontend edits should update the webview
without restarting the Rust process.
**Windows Development**
```powershell

View File

@ -0,0 +1,73 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
#[derive(Deserialize, Serialize, ToSchema)]
pub struct CreateLoginChallengeRequest {}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct ReviewLoginChallengeRequest {
pub approval_token: String,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct DecideLoginChallengeRequest {
pub approval_token: String,
pub approve: bool,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct PollLoginChallengeRequest {
pub device_token: String,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct CreateLoginChallengeResponse {
pub success: bool,
pub device_token: String,
pub verification_url: String,
pub confirmation_code: String,
pub expires_at: DateTime<Utc>,
pub poll_interval_seconds: u32,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct ReviewLoginChallengeResponse {
pub success: bool,
pub status: LoginChallengeState,
pub maybe_failure_type: Option<LoginChallengeFailure>,
pub confirmation_code: String,
pub requesting_ip: String,
pub expires_at: DateTime<Utc>,
pub username: String,
}
#[derive(Deserialize, Serialize, ToSchema)]
pub struct LoginChallengeResponse {
pub success: bool,
pub status: LoginChallengeState,
pub maybe_failure_type: Option<LoginChallengeFailure>,
/// Present only to the device after the redemption transaction commits.
#[serde(skip_serializing_if = "Option::is_none")]
pub maybe_signed_session: Option<String>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum LoginChallengeState {
Pending,
Approved,
Redeemed,
Failed,
#[serde(other)]
Unknown,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum LoginChallengeFailure {
UserDeclined,
Expired,
#[serde(other)]
Unknown,
}

View File

@ -2,4 +2,5 @@ pub mod change_password;
pub mod edit_email;
pub mod edit_username;
pub mod login;
pub mod session_info;
pub mod session_info;
pub mod login_challenges;

View File

@ -1,11 +1,12 @@
use crate::common::responses::user_details_light::UserDetailsLight;
use enums::by_table::users::user_feature_flag::UserFeatureFlag;
use serde_derive::Serialize;
use serde_derive::{Deserialize, Serialize};
use serde::{Deserialize as DeserializeTrait, Deserializer};
use std::collections::BTreeSet;
use tokens::tokens::users::UserToken;
use utoipa::ToSchema;
#[derive(Serialize, Copy, Clone, ToSchema)]
#[derive(Serialize, Deserialize, Copy, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum FakeYouPlan {
Free,
@ -14,7 +15,7 @@ pub enum FakeYouPlan {
Pro,
}
#[derive(Serialize, Copy, Clone, ToSchema)]
#[derive(Serialize, Deserialize, Copy, Clone, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum StorytellerStreamPlan {
Free,
@ -23,7 +24,7 @@ pub enum StorytellerStreamPlan {
Pro,
}
#[derive(Serialize, ToSchema)]
#[derive(Serialize, Deserialize, ToSchema)]
pub struct SessionUserInfo {
pub core_info: UserDetailsLight,
@ -41,6 +42,7 @@ pub struct SessionUserInfo {
/// Collection of feature / rollout flags
/// This is the proper place to detect if a user has access to some rollout (non-paywall) feature.
/// NB: The BTreeSet maintains order so React doesn't introduce re-render state bugs when order changes
#[serde(default, deserialize_with = "deserialize_known_feature_flags")]
pub maybe_feature_flags: BTreeSet<UserFeatureFlag>,
// Premium plans:
@ -76,7 +78,7 @@ pub struct SessionUserInfo {
pub can_delete_users: bool,
}
#[derive(Serialize, ToSchema)]
#[derive(Serialize, Deserialize, ToSchema)]
pub struct SessionOnboardingState {
/// If true, the user hasn't set their email.
pub email_not_set: bool,
@ -91,9 +93,18 @@ pub struct SessionOnboardingState {
pub username_not_customized: bool,
}
#[derive(Serialize, ToSchema)]
#[derive(Serialize, Deserialize, ToSchema)]
pub struct SessionInfoSuccessResponse {
pub success: bool,
pub logged_in: bool,
pub user: Option<SessionUserInfo>,
}
// Server rollouts may introduce flags before a desktop release understands them.
// Ignore only unknown flag names; malformed values and authentication fields
// still fail decoding. Unknown flags never grant a client-side capability.
fn deserialize_known_feature_flags<'de, D>(deserializer: D) -> Result<BTreeSet<UserFeatureFlag>, D::Error>
where D: Deserializer<'de> {
let names = Vec::<String>::deserialize(deserializer)?;
Ok(names.into_iter().filter_map(|name| UserFeatureFlag::from_str(&name).ok()).collect())
}

View File

@ -0,0 +1,27 @@
# artcraft_client
Rust HTTP endpoint bindings used by the ArtCraft Tauri desktop app.
## Endpoint layout
- Each HTTP endpoint binding must live in its own descriptively named `.rs` file.
This applies to both free functions and methods implemented on a shared client.
Do not combine several routes into a catch-all file such as `login_challenges.rs`
or `password_auth.rs`.
- Group related bindings in a directory module. Keep `mod.rs` for module declarations;
it must not contain endpoint implementations. For example:
`endpoints/users/login_challenges/create_login_challenge.rs` and
`endpoints/users/login_challenges/poll_login_challenge.rs`.
- Keep each endpoint's route constant, request construction, and endpoint-specific
request/response types in its file. Keep shared wire types in `artcraft_api_defs`
or a dedicated shared type module; do not duplicate them across endpoint files.
- Put shared HTTP transport, client setup, and common error handling in a separate
utility module. A transport module must not accumulate endpoint bindings.
- Update callers to import types from their new modules when splitting bindings.
Preserve request methods, paths, headers, error behavior, and cookie handling.
## Validation
Run `cargo check --offline -p artcraft_client` for client changes. For native login
bindings, also run `SQLX_OFFLINE=true cargo test --offline -p artcraft --lib
login_bridge_tests`; these tests use local HTTP fixtures and temporary cookie jars.

View File

@ -19,6 +19,7 @@ path = "src/lib.rs"
# Internal
artcraft_api_defs.workspace = true
artcraft_client_identity.workspace = true
cloudflare_errors.workspace = true
enums.workspace = true
errors.workspace = true

View File

@ -29,7 +29,7 @@ pub async fn get_media_file(api_host: &ApiHost, media_file_token: &MediaFileToke
debug!("Requesting {:?}", &url);
let response = http_get_anonymous(url).await?;
let response = http_get_anonymous(api_host, url).await?;
let response = filter_bad_response(response).await?;
let response_body = &response.text().await
.map_err(|err| StorytellerError::Api(ApiError::from(err)))?;

View File

@ -3,7 +3,8 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use chrono::{DateTime, Utc};
@ -11,7 +12,6 @@ use enums::common::generation_provider::GenerationProvider;
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -56,8 +56,7 @@ pub async fn legacy_upload_media_file_from_file<P: AsRef<Path>>(
//let mut file = File::open(path)?;
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(args.api_host)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
@ -86,7 +85,6 @@ pub async fn legacy_upload_media_file_from_file<P: AsRef<Path>>(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -3,7 +3,8 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use enums::common::generation_provider::GenerationProvider;
@ -11,7 +12,6 @@ use chrono::{DateTime, Utc};
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::fs::File;
use std::io::Read;
@ -72,8 +72,7 @@ pub async fn upload_image_media_file_from_bytes(
debug!("Requesting {:?}", &url);
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(args.api_host)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
@ -95,7 +94,6 @@ pub async fn upload_image_media_file_from_bytes(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -3,7 +3,8 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use chrono::{DateTime, Utc};
@ -11,7 +12,6 @@ use enums::common::generation_provider::GenerationProvider;
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -65,8 +65,7 @@ pub async fn upload_image_media_file_from_file_with_idempotency_token<P: AsRef<P
//let mut file = File::open(path)?;
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(args.api_host)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
@ -95,7 +94,6 @@ pub async fn upload_image_media_file_from_file_with_idempotency_token<P: AsRef<P
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -1,7 +1,8 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::api_error::ApiError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use enums::common::generation_provider::GenerationProvider;
@ -9,7 +10,6 @@ use chrono::{DateTime, Utc};
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -32,8 +32,7 @@ pub async fn upload_new_engine_asset_from_file<P: AsRef<Path>>(
debug!("Requesting {:?}", &url);
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(api_host)
.build()?;
let file_bytes = std::fs::read(path.as_ref())?;
@ -49,7 +48,6 @@ pub async fn upload_new_engine_asset_from_file<P: AsRef<Path>>(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = maybe_creds {

View File

@ -1,7 +1,8 @@
use crate::credentials::storyteller_credential_set::StorytellerCredentialSet;
use crate::error::api_error::ApiError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use crate::utils::http_get_anonymous::http_get_anonymous;
use enums::common::generation_provider::GenerationProvider;
@ -9,7 +10,6 @@ use chrono::{DateTime, Utc};
use uuid_utils::uuid::generate_random_uuid;
use log::debug;
use reqwest::multipart::{Form, Part};
use reqwest::Client;
use serde_derive::{Deserialize, Serialize};
use std::path::Path;
use tokens::tokens::batch_generations::BatchGenerationToken;
@ -58,8 +58,7 @@ pub async fn upload_video_media_file_from_file<P: AsRef<Path>>(
debug!("Requesting {:?}", &url);
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(args.api_host)
.build()?;
let file_bytes = std::fs::read(args.path.as_ref())?;
@ -78,7 +77,6 @@ pub async fn upload_video_media_file_from_file<P: AsRef<Path>>(
}
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = args.maybe_creds {

View File

@ -7,3 +7,4 @@ pub mod media_files;
pub mod prompts;
pub mod stripe_artcraft;
pub mod subscriptions;
pub mod users;

View File

@ -0,0 +1,16 @@
use artcraft_api_defs::users::login_challenges::{CreateLoginChallengeRequest, CreateLoginChallengeResponse};
use reqwest::Method;
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
pub const CREATE_PATH: &str = "/v1/login_challenges/create";
impl LoginChallengeClient {
pub async fn create(&self) -> Result<CreateLoginChallengeResponse, LoginChallengeClientError> {
let request = self
.request(Method::POST, CREATE_PATH)
.json(&CreateLoginChallengeRequest {});
let (result, _) = self.send(request, CREATE_PATH).await?;
Ok(result)
}
}

View File

@ -0,0 +1,2 @@
pub mod create_login_challenge;
pub mod poll_login_challenge;

View File

@ -0,0 +1,30 @@
use artcraft_api_defs::users::login_challenges::{LoginChallengeResponse, PollLoginChallengeRequest};
use reqwest::Method;
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
pub const POLL_PATH: &str = "/v1/login_challenges/poll";
// Deliberately no Debug/Serialize: the wire result contains a bearer credential.
pub struct PollLoginChallengeResult {
pub response: LoginChallengeResponse,
pub session_set_cookie: Option<String>,
}
impl LoginChallengeClient {
pub async fn poll(
&self,
device_token: &str,
) -> Result<PollLoginChallengeResult, LoginChallengeClientError> {
let request = self
.request(Method::POST, POLL_PATH)
.json(&PollLoginChallengeRequest {
device_token: device_token.to_owned(),
});
let (response, session_set_cookie) = self.send(request, POLL_PATH).await?;
Ok(PollLoginChallengeResult {
response,
session_set_cookie,
})
}
}

View File

@ -0,0 +1,5 @@
pub mod login_challenges;
pub mod password_auth_response;
pub mod password_login;
pub mod password_signup;
pub mod session_info;

View File

@ -0,0 +1,8 @@
use serde::Deserialize;
// No Debug: the response contains a bearer credential.
#[derive(Deserialize)]
pub struct PasswordAuthResponse {
pub success: bool,
pub signed_session: Option<String>,
}

View File

@ -0,0 +1,20 @@
use reqwest::Method;
use serde::{Deserialize, Serialize};
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
use super::password_auth_response::PasswordAuthResponse;
pub const LOGIN_PATH: &str = "/v1/login";
// No Debug: the request contains credentials.
#[derive(Deserialize, Serialize)]
pub struct PasswordLoginRequest {
pub username_or_email: String,
pub password: String,
}
impl LoginChallengeClient {
pub async fn password_login(&self, request: &PasswordLoginRequest) -> Result<(PasswordAuthResponse, Option<String>), LoginChallengeClientError> {
self.send(self.request(Method::POST, LOGIN_PATH).json(request), LOGIN_PATH).await
}
}

View File

@ -0,0 +1,23 @@
use reqwest::Method;
use serde::{Deserialize, Serialize};
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
use super::password_auth_response::PasswordAuthResponse;
pub const SIGNUP_PATH: &str = "/v1/create_account";
// No Debug: the request contains credentials.
#[derive(Deserialize, Serialize)]
pub struct PasswordSignupRequest {
pub username: String,
pub email_address: String,
pub password: String,
pub password_confirmation: String,
pub signup_source: String,
}
impl LoginChallengeClient {
pub async fn password_signup(&self, request: &PasswordSignupRequest) -> Result<(PasswordAuthResponse, Option<String>), LoginChallengeClientError> {
self.send(self.request(Method::POST, SIGNUP_PATH).json(request), SIGNUP_PATH).await
}
}

View File

@ -0,0 +1,19 @@
use artcraft_api_defs::users::session_info::SessionInfoSuccessResponse;
use reqwest::Method;
use crate::utils::login_challenge_client::{LoginChallengeClient, LoginChallengeClientError};
pub const SESSION_PATH: &str = "/v1/session";
impl LoginChallengeClient {
pub async fn session(
&self,
signed_session: &str,
) -> Result<SessionInfoSuccessResponse, LoginChallengeClientError> {
let request = self
.request(Method::GET, SESSION_PATH)
.header("Cookie", format!("session={signed_session}"));
let (result, _) = self.send(request, SESSION_PATH).await?;
Ok(result)
}
}

View File

@ -1,4 +1,6 @@
use artcraft_client_identity::origins::{ARTCRAFT_DESKTOP_DEVELOPMENT_ORIGIN, ARTCRAFT_DESKTOP_ORIGIN};
const HTTP_SCHEME: &str = "http";
const HTTPS_SCHEME: &str = "https";
@ -27,6 +29,15 @@ impl ApiHost {
}
}
/// The `Origin` the desktop client declares to this API.
pub fn request_origin(&self) -> &'static str {
match self {
ApiHost::Storyteller => ARTCRAFT_DESKTOP_ORIGIN,
ApiHost::FakeYou => ARTCRAFT_DESKTOP_ORIGIN,
ApiHost::Localhost { .. } => ARTCRAFT_DESKTOP_DEVELOPMENT_ORIGIN,
}
}
pub fn scheme(&self) -> &'static str {
match self {
ApiHost::Storyteller => HTTPS_SCHEME,

View File

@ -3,10 +3,10 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@ -21,13 +21,11 @@ pub async fn basic_json_delete_request<Req: Serialize, Res: DeserializeOwned>(
info!("DELETE {:?}", &url);
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(api_host)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.delete(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON)
.header("Content-Type", APPLICATION_JSON);

View File

@ -3,10 +3,10 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@ -20,13 +20,11 @@ pub async fn basic_json_get_request<Res: DeserializeOwned>(
debug!("Requesting {:?}", &url);
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(api_host)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.get(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = maybe_creds {

View File

@ -3,10 +3,10 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
@ -30,13 +30,11 @@ pub async fn basic_json_post_request<Req: Serialize, Res: DeserializeOwned>(
info!("Requesting {:?}", &url);
}
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(api_host)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON)
.header("Content-Type", APPLICATION_JSON);

View File

@ -3,11 +3,11 @@ use crate::error::api_error::ApiError;
use crate::error::client_error::ClientError;
use crate::error::storyteller_error::StorytellerError;
use crate::utils::api_host::ApiHost;
use crate::utils::constants::{APPLICATION_JSON, USER_AGENT};
use crate::utils::constants::APPLICATION_JSON;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
use crate::utils::filter_bad_response::filter_bad_response;
use errors::AnyhowResult;
use log::{debug, info};
use reqwest::Client;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@ -26,13 +26,11 @@ pub async fn basic_query_string_post_request<Res: DeserializeOwned>(
debug!("Requesting {:?}", &url);
let client = Client::builder()
.gzip(true)
let client = storyteller_client_builder(api_host)
.build()
.map_err(|err| StorytellerError::Client(ClientError::from(err)))?;
let mut request_builder = client.post(url)
.header("User-Agent", USER_AGENT)
.header("Accept", APPLICATION_JSON);
if let Some(creds) = maybe_creds {

View File

@ -1,4 +1 @@
pub const USER_AGENT: &str = "storyteller-client/1.0";
pub const APPLICATION_JSON : &str = "application/json";

View File

@ -1,14 +1,12 @@
use crate::error::api_error::ApiError;
use reqwest::Client;
const USER_AGENT: &str = "storyteller-client/1.0";
use crate::utils::api_host::ApiHost;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
pub async fn http_get_anonymous(url: String) -> Result<reqwest::Response, ApiError> {
let client = Client::builder()
.gzip(true)
pub async fn http_get_anonymous(api_host: &ApiHost, url: String) -> Result<reqwest::Response, ApiError> {
let client = storyteller_client_builder(api_host)
.build()?;
let response = client.get(url)
.header("User-Agent", USER_AGENT)
.header("Accept", "application/json")
//.header("Accept-Encoding", "gzip, deflate, br")
.send()

View File

@ -0,0 +1,150 @@
use std::time::Duration;
use log::{info, warn};
use reqwest::header::SET_COOKIE;
use reqwest::{Client, Method, RequestBuilder};
use serde::de::DeserializeOwned;
use url::Url;
use crate::utils::api_host::ApiHost;
use crate::utils::storyteller_client_builder::storyteller_client_builder;
/// Native transport for the session bridge. No request/response bodies, cookies,
/// or challenge credentials are logged, even at debug level. Never follows redirects.
#[derive(Clone)]
pub struct LoginChallengeClient {
client: Client,
api_host: ApiHost,
}
#[derive(Debug)]
pub struct LoginChallengeClientError {
pub status: Option<u16>,
pub message: &'static str,
}
impl LoginChallengeClient {
pub fn new(api_host: &ApiHost) -> Result<Self, LoginChallengeClientError> {
let mut builder = storyteller_client_builder(api_host);
if matches!(api_host, ApiHost::Localhost { .. }) {
builder = builder.no_proxy();
}
let client = builder
.timeout(Duration::from_secs(15))
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(|_| LoginChallengeClientError::invalid("Unable to initialize login client"))?;
Ok(Self {
client,
api_host: api_host.clone(),
})
}
pub fn api_origin(&self) -> String {
self.api_host.to_api_hostname_and_scheme()
}
pub fn api_url(&self) -> Url {
Url::parse(&format!("{}/", self.api_origin())).expect("ApiHost must produce a valid origin")
}
pub fn allows_verification_url(&self, value: &str) -> bool {
let Ok(url) = Url::parse(value) else {
return false;
};
let origin_allowed = match self.api_host {
ApiHost::Localhost { .. } => ["http://localhost:4200", "http://127.0.0.1:4200", "http://localhost:4201", "http://127.0.0.1:4201"]
.contains(&url.origin().ascii_serialization().as_str()),
ApiHost::Storyteller => ["https://app.getartcraft.com", "https://getartcraft.com", "https://www.getartcraft.com"]
.contains(&url.origin().ascii_serialization().as_str()),
ApiHost::FakeYou => false,
};
origin_allowed
&& url.username().is_empty()
&& url.password().is_none()
&& url.path() == "/login/desktop"
&& url.query().is_none()
&& url
.fragment()
.and_then(|f| f.strip_prefix("approval_token="))
.map(|s| {
s.len() == 43
&& s
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
})
.unwrap_or(false)
}
pub(crate) fn request(&self, method: Method, path: &str) -> RequestBuilder {
self
.client
.request(method, format!("{}{path}", self.api_origin()))
.header("Accept", "application/json")
}
pub(crate) async fn send<T: DeserializeOwned>(
&self,
request: RequestBuilder,
path: &str,
) -> Result<(T, Option<String>), LoginChallengeClientError> {
let origin = self.api_origin();
info!("Website login request: origin={} path={}", origin, path);
let response = request.send().await.map_err(|_| {
warn!(
"Website login network failure: origin={} path={}",
origin, path
);
LoginChallengeClientError::invalid("Unable to reach the login server")
})?;
let status = response.status();
if !status.is_success() {
warn!(
"Website login HTTP failure: origin={} path={} status={}",
origin,
path,
status.as_u16()
);
return Err(LoginChallengeClientError {
status: Some(status.as_u16()),
message: "Login server rejected the request",
});
}
let session_cookie = response
.headers()
.get_all(SET_COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.find(|v| {
cookie::Cookie::parse(*v)
.map(|c| c.name() == "session")
.unwrap_or(false)
})
.map(str::to_owned);
let body = response.json().await.map_err(|_| {
warn!(
"Website login invalid response: origin={} path={}",
origin, path
);
LoginChallengeClientError::invalid("Invalid response from login server")
})?;
Ok((body, session_cookie))
}
}
impl LoginChallengeClientError {
pub fn invalid(message: &'static str) -> Self {
Self {
status: None,
message,
}
}
}
impl std::fmt::Display for LoginChallengeClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} (HTTP {:?})", self.message, self.status)
}
}
impl std::error::Error for LoginChallengeClientError {}

View File

@ -4,6 +4,8 @@ pub mod basic_json_post_request;
pub (crate) mod basic_query_string_post_request;
pub (crate) mod filter_bad_response;
pub (crate) mod http_get_anonymous;
pub (crate) mod storyteller_client_builder;
pub mod api_host;
pub mod constants;
pub mod status_codes;
pub mod login_challenge_client;

View File

@ -0,0 +1,17 @@
use artcraft_client_identity::user_agents::ARTCRAFT_DESKTOP_USER_AGENT;
use reqwest::header::{HeaderMap, HeaderValue, ORIGIN};
use reqwest::{Client, ClientBuilder};
use crate::utils::api_host::ApiHost;
/// Every request to our API is built from this so the desktop client identifies itself
/// consistently (`User-Agent` and `Origin`). Only use it for Storyteller / ArtCraft APIs.
pub(crate) fn storyteller_client_builder(api_host: &ApiHost) -> ClientBuilder {
let mut headers = HeaderMap::new();
headers.insert(ORIGIN, HeaderValue::from_static(api_host.request_origin()));
Client::builder()
.user_agent(ARTCRAFT_DESKTOP_USER_AGENT)
.default_headers(headers)
.gzip(true)
}

View File

@ -1,4 +1,5 @@
# Don't restart the dev server on Rust changes
crates/
Cargo.toml
Cargo.lock
# Rust sources and Cargo manifests must remain watched for `cargo tauri dev`.
# Vite owns frontend reloads; build artifacts must not trigger Rust rebuilds.
target/
node_modules/
dist/

View File

@ -1,10 +1,10 @@
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::core::state::app_startup_time::AppStartupTime;
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
use anyhow::anyhow;
use chrono::TimeDelta;
use errors::AnyhowResult;
use log::{error, info};
use once_cell::sync::Lazy;
use reqwest::Url;
use artcraft_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
@ -13,24 +13,13 @@ use tauri::{AppHandle, Manager};
use tauri_plugin_http::reqwest_cookie_store::CookieStore;
use tauri_plugin_http::Http;
const STORYTELLER_ROOT_COOKIE_URL_STR: &str = "https://api.storyteller.ai/";
static STORYTELLER_ROOT_COOKIE_URL: Lazy<Url> = Lazy::new(|| {
Url::parse(STORYTELLER_ROOT_COOKIE_URL_STR).expect("URL should parse")
});
const AVT_COOKIE_NAME : &str = "visitor";
const SESSION_COOKIE_NAME : &str = "session";
const AVT_COOKIE_NAME: &str = "visitor";
const SESSION_COOKIE_NAME: &str = "session";
/// There's some kind of race condition that we need to wait for before inspecting cookies.
const RACE_CONDITION_WAIT_TIME: TimeDelta = TimeDelta::milliseconds(5000);
pub async fn persist_storyteller_cookies_task(
app: &AppHandle,
storyteller_credential_manager: &StorytellerCredentialManager,
app_startup_time: &AppStartupTime,
) -> AnyhowResult<()> {
pub async fn persist_storyteller_cookies_task(app: &AppHandle, storyteller_credential_manager: &StorytellerCredentialManager, app_startup_time: &AppStartupTime) -> AnyhowResult<()> {
//if app_startup_time.time_delta_since() < RACE_CONDITION_WAIT_TIME {
// // NB: There's an issue when the "main window thread" inquires about the
// // webview cookies shortly after app startup. When it attempts to dump the
@ -41,33 +30,30 @@ pub async fn persist_storyteller_cookies_task(
//}
let maybe_http = app.try_state::<Http>();
let http = match maybe_http {
None => {
error!("No HTTP plugin found");
return Err(anyhow!("No HTTP plugin found"));
}
},
Some(http) => http,
};
match http.cookies_jar.store.lock() {
Err(err) => {
error!("Failed to lock cookie jar: {:?}", err);
return Err(anyhow!("Failed to lock cookie jar"));
}
},
Ok(cookie_jar) => {
sync_tauri_credentials(&cookie_jar, storyteller_credential_manager)?;
}
sync_tauri_credentials(&cookie_jar, storyteller_credential_manager, &storyteller_cookie_url(app)?)?;
},
}
Ok(())
}
fn sync_tauri_credentials(
cookie_store: &CookieStore,
storyteller_credential_manager: &StorytellerCredentialManager,
) -> AnyhowResult<()> {
let current_http_plugin_credentials = get_credentials_from_cookie_store(cookie_store)?;
pub(crate) fn sync_tauri_credentials(cookie_store: &CookieStore, storyteller_credential_manager: &StorytellerCredentialManager, api_url: &Url) -> AnyhowResult<()> {
let current_http_plugin_credentials = get_credentials_from_cookie_store(cookie_store, api_url)?;
let mut replace_credentials = true;
@ -78,31 +64,80 @@ fn sync_tauri_credentials(
replace_credentials = false;
}
}
if replace_credentials {
info!("Syncing ArtCraft credentials ...");
storyteller_credential_manager.set_credentials(&current_http_plugin_credentials)?;
// NB: tauri-plugin-http stores the credentials on disk, so we can defer to that for now.
//storyteller_credential_manager.persist_all_to_disk()?;
}
Ok(())
}
pub fn get_credentials_from_cookie_store(cookie_jar: &CookieStore) -> AnyhowResult<StorytellerCredentialSet> {
pub fn get_credentials_from_cookie_store(cookie_jar: &CookieStore, api_url: &Url) -> AnyhowResult<StorytellerCredentialSet> {
let mut avt_cookie = None;
let mut session_cookie = None;
for cookie in cookie_jar.iter_unexpired() {
if let Some(avt) = StorytellerAvtCookie::maybe_from_cookie(&cookie) {
avt_cookie = Some(avt);
} else if let Some(session) = StorytellerSessionCookie::maybe_from_cookie(&cookie) {
session_cookie = Some(session);
// Only cookies applicable to our API origin can become ArtCraft credentials.
for (name, value) in cookie_jar.get_request_values(api_url) {
match name {
AVT_COOKIE_NAME => avt_cookie = Some(StorytellerAvtCookie::new(value.to_owned())),
SESSION_COOKIE_NAME => session_cookie = Some(StorytellerSessionCookie::new(value.to_owned())),
_ => {},
}
}
Ok(StorytellerCredentialSet::initialize(
avt_cookie,
session_cookie,
))
Ok(StorytellerCredentialSet::initialize(avt_cookie, session_cookie))
}
pub(crate) fn storyteller_cookie_url(app: &AppHandle) -> AnyhowResult<Url> {
let config = app.try_state::<AppEnvConfigs>().ok_or_else(|| anyhow!("API configuration unavailable"))?;
Ok(Url::parse(&format!("{}/", config.storyteller_host.to_api_hostname_and_scheme()))?)
}
#[cfg(test)]
mod login_bridge_tests {
use super::*;
use crate::core::state::data_dir::app_data_root::AppDataRoot;
use tauri_plugin_http::reqwest_cookie_store::RawCookie;
#[test]
fn approved_response_cookie_reaches_native_credentials() {
let directory = tempfile::tempdir().unwrap();
let root = AppDataRoot::create_existing(directory.path()).unwrap();
let manager = StorytellerCredentialManager::initialize_empty(&root);
let mut jar = CookieStore::default();
let url = Url::parse("https://api.storyteller.ai/v1/login_challenges/poll").unwrap();
jar.store_response_cookies([RawCookie::parse("session=signed_backend_cookie; Secure; HttpOnly; Path=/; Max-Age=3600").unwrap().into_owned(), RawCookie::parse("visitor=existing_visitor; Secure; Path=/; Max-Age=3600").unwrap().into_owned()].into_iter(), &url);
sync_tauri_credentials(&jar, &manager, &url).unwrap();
let credentials = manager.get_credentials_required().unwrap();
assert_eq!(credentials.session.unwrap().as_str(), "signed_backend_cookie");
assert_eq!(credentials.avt.unwrap().as_str(), "existing_visitor");
// Retrying the same successful poll is idempotent for native credentials too.
sync_tauri_credentials(&jar, &manager, &url).unwrap();
assert_eq!(manager.get_credentials_required().unwrap().session.unwrap().as_str(), "signed_backend_cookie");
}
#[test]
fn unrelated_and_expired_cookies_cannot_become_artcraft_sessions() {
let url = Url::parse("https://api.storyteller.ai/").unwrap();
let mut jar = CookieStore::default();
jar.store_response_cookies([RawCookie::parse("session=unrelated; Path=/; Max-Age=3600").unwrap().into_owned()].into_iter(), &Url::parse("https://unrelated.example/").unwrap());
assert!(get_credentials_from_cookie_store(&jar, &url).unwrap().session.is_none());
jar.store_response_cookies([RawCookie::parse("session=expired; Secure; Path=/; Max-Age=0").unwrap().into_owned()].into_iter(), &url);
assert!(get_credentials_from_cookie_store(&jar, &url).unwrap().session.is_none());
}
#[test]
fn configured_local_api_does_not_import_production_cookies() {
let production = Url::parse("https://api.storyteller.ai/").unwrap();
let local = Url::parse("http://localhost:12345/").unwrap();
let mut jar = CookieStore::default();
jar.store_response_cookies([RawCookie::parse("session=production; Secure; Path=/").unwrap().into_owned()].into_iter(), &production);
assert!(get_credentials_from_cookie_store(&jar, &local).unwrap().session.is_none());
jar.store_response_cookies([RawCookie::parse("session=development; Path=/").unwrap().into_owned()].into_iter(), &local);
assert_eq!(get_credentials_from_cookie_store(&jar, &local).unwrap().session.unwrap().as_str(), "development");
assert_eq!(get_credentials_from_cookie_store(&jar, &production).unwrap().session.unwrap().as_str(), "production");
}
}

View File

@ -63,6 +63,13 @@ use crate::services::sora::commands::sora_logout_command::sora_logout_command;
use crate::services::sora::state::sora_credential_manager::SoraCredentialManager;
use crate::services::sora::state::sora_task_queue::SoraTaskQueue;
use crate::services::sora::threads::sora_task_polling::sora_task_polling_thread::sora_task_polling_thread;
use crate::services::storyteller::commands::login_bridge::DesktopLoginBridgeState;
use crate::services::storyteller::commands::storyteller_cancel_login_challenge_command::storyteller_cancel_login_challenge_command;
use crate::services::storyteller::commands::storyteller_create_login_challenge_command::storyteller_create_login_challenge_command;
use crate::services::storyteller::commands::storyteller_get_login_session_command::storyteller_get_login_session_command;
use crate::services::storyteller::commands::storyteller_password_login_command::storyteller_password_login_command;
use crate::services::storyteller::commands::storyteller_password_signup_command::storyteller_password_signup_command;
use crate::services::storyteller::commands::storyteller_poll_login_challenge_command::storyteller_poll_login_challenge_command;
use crate::services::storyteller::commands::storyteller_get_credits_command::storyteller_get_credits_command;
use crate::services::storyteller::commands::storyteller_get_subscription_command::storyteller_get_subscription_command;
use crate::services::storyteller::commands::storyteller_purge_credentials_command::storyteller_purge_credentials_command;
@ -201,6 +208,7 @@ pub fn run() {
})
.manage(app_data_root)
.manage(app_env_configs)
.manage(DesktopLoginBridgeState::default())
.manage(app_preferences)
.manage(artcraft_platform_info)
.manage(artcraft_usage_tracker)
@ -259,6 +267,12 @@ pub fn run() {
set_provider_order_command,
sora_get_credential_info_command,
sora_logout_command,
storyteller_get_login_session_command,
storyteller_password_login_command,
storyteller_password_signup_command,
storyteller_create_login_challenge_command,
storyteller_poll_login_challenge_command,
storyteller_cancel_login_challenge_command,
storyteller_get_credits_command,
storyteller_get_subscription_command,
storyteller_open_credits_purchase_command,

View File

@ -0,0 +1,17 @@
# Tauri Commands
- Put each `#[tauri::command]` function in its own `.rs` file module named after
that command, such as `storyteller_create_login_challenge_command.rs`. Do not
collect multiple commands in a catch-all `*_commands.rs` file.
- Keep `mod.rs` for module declarations. Put shared state, response/error types,
and implementation helpers in separate support modules, with the narrowest
visibility needed by their callers.
- Update the imports used by `tauri::generate_handler!` when moving commands.
Preserve IPC command names and arguments unless changing that contract is
explicitly part of the task.
- Authentication HTTP requests run in Rust through `artcraft_client` endpoint
bindings. The frontend invokes Tauri commands; it does not call the API
directly, and desktop commands do not connect to the backend MySQL database.
- For login bridge changes, run the existing native fixture tests with
`SQLX_OFFLINE=true cargo test --offline -p artcraft --lib login_bridge_tests`.
These tests use loopback HTTP servers and temporary cookie stores.

View File

@ -0,0 +1,340 @@
use std::collections::HashMap;
use std::sync::Arc;
use artcraft_api_defs::users::login_challenges::{LoginChallengeFailure, LoginChallengeState};
use artcraft_api_defs::users::session_info::SessionUserInfo;
use artcraft_client::endpoints::users::password_login::PasswordLoginRequest;
use artcraft_client::endpoints::users::password_signup::PasswordSignupRequest;
use artcraft_client::utils::api_host::ApiHost;
use artcraft_client::utils::login_challenge_client::{
LoginChallengeClient, LoginChallengeClientError,
};
use chrono::{DateTime, Utc};
use log::{info, warn};
use serde::Serialize;
use tauri::{AppHandle, Manager};
use tauri_plugin_http::reqwest_cookie_store::{CookieStoreMutex, RawCookie};
use tauri_plugin_http::Http;
use tokio::sync::Mutex;
use uuid_utils::uuid::generate_random_uuid;
use crate::core::threads::main_window_thread::persist_storyteller_cookies_task::get_credentials_from_cookie_store;
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
const MAX_PENDING_CHALLENGES: usize = 8;
/// All bearer credentials stay in Rust. The UI holds only a local lookup handle.
#[derive(Default)]
pub struct DesktopLoginBridgeState {
pending: Mutex<HashMap<String, PendingChallenge>>,
}
#[derive(Clone)]
struct PendingChallenge {
device_token: String,
expires_at: DateTime<Utc>,
client: LoginChallengeClient,
}
#[derive(Serialize)]
pub struct DesktopLoginChallenge {
pub challenge_id: String,
pub verification_url: String,
pub confirmation_code: String,
pub expires_at: DateTime<Utc>,
pub poll_interval_seconds: u32,
}
#[derive(Serialize)]
pub struct DesktopLoginOutcome {
pub status: LoginChallengeState,
pub maybe_failure_type: Option<LoginChallengeFailure>,
pub maybe_user: Option<SessionUserInfo>,
}
#[derive(Debug, Serialize)]
pub struct DesktopLoginError {
pub status: Option<u16>,
pub message: String,
pub retryable: bool,
}
impl DesktopLoginError {
fn local(message: &str) -> Self {
Self {
status: None,
message: message.to_owned(),
retryable: false,
}
}
pub(super) fn from_client(origin: &str, error: LoginChallengeClientError) -> Self {
warn!(
"Website login failed: origin={} status={:?} reason={}",
origin, error.status, error.message
);
Self {
retryable: error
.status
.map(|s| s == 429 || s >= 500)
.unwrap_or(error.message == "Unable to reach the login server"),
status: error.status,
message: format!("{}: {} (HTTP {:?})", origin, error.message, error.status),
}
}
}
pub(super) async fn current_login_session(
client: &LoginChallengeClient,
jar: &Arc<CookieStoreMutex>,
) -> Result<Option<SessionUserInfo>, DesktopLoginError> {
let credentials = {
let store = jar
.store
.lock()
.map_err(|_| DesktopLoginError::local("HTTP cookie store unavailable"))?;
get_credentials_from_cookie_store(&store, &client.api_url())
.map_err(|_| DesktopLoginError::local("Unable to read session cookie"))?
};
let Some(signed) = credentials.session else {
return Ok(None);
};
let session = match client.session(signed.as_str()).await {
Ok(session) => session,
Err(error) if error.status == Some(401) => return Ok(None),
Err(error) => return Err(DesktopLoginError::from_client(&client.api_origin(), error)),
};
Ok(
session
.user
.filter(|_| session.success && session.logged_in),
)
}
pub(super) async fn password_auth(
host: &ApiHost,
manager: &StorytellerCredentialManager,
jar: &Arc<CookieStoreMutex>,
login: Option<PasswordLoginRequest>,
signup: Option<PasswordSignupRequest>,
) -> Result<SessionUserInfo, DesktopLoginError> {
let client = LoginChallengeClient::new(host)
.map_err(|e| DesktopLoginError::from_client(&host.to_api_hostname_and_scheme(), e))?;
let response = match (login, signup) {
(Some(request), None) => client.password_login(&request).await,
(None, Some(request)) => client.password_signup(&request).await,
_ => return Err(DesktopLoginError::local("Invalid authentication request")),
}
.map_err(|e| DesktopLoginError::from_client(&client.api_origin(), e))?;
let (response, cookie) = response;
if !response.success {
return Err(DesktopLoginError::local(
"Sign-in failed. Check your account details and try again.",
));
}
let signed = response
.signed_session
.ok_or_else(|| DesktopLoginError::local("Login server did not issue a session"))?;
let cookie =
cookie.ok_or_else(|| DesktopLoginError::local("Login server did not set a session cookie"))?;
let (cookie, user) = verify_session(&client, &signed, cookie).await?;
install_session_cookie(&client, &signed, cookie, manager, jar)?;
persist_session_cookie(jar).await?;
Ok(user)
}
pub(super) fn http_cookie_jar(app: &AppHandle) -> Result<Arc<CookieStoreMutex>, DesktopLoginError> {
Ok(
app
.try_state::<Http>()
.ok_or_else(|| DesktopLoginError::local("HTTP cookie store unavailable"))?
.cookies_jar
.clone(),
)
}
pub(super) async fn begin_challenge(
host: &ApiHost,
state: &DesktopLoginBridgeState,
) -> Result<DesktopLoginChallenge, DesktopLoginError> {
let client = LoginChallengeClient::new(host)
.map_err(|e| DesktopLoginError::from_client(&host.to_api_hostname_and_scheme(), e))?;
let created = client
.create()
.await
.map_err(|e| DesktopLoginError::from_client(&client.api_origin(), e))?;
if !created.success
|| !client.allows_verification_url(&created.verification_url)
|| created.device_token.len() != 43
|| created.expires_at <= Utc::now()
{
return Err(DesktopLoginError::local(
"Invalid login challenge or website/API environment mismatch",
));
}
let mut pending = state.pending.lock().await;
pending.retain(|_, value| value.expires_at > Utc::now());
if pending.len() >= MAX_PENDING_CHALLENGES {
return Err(DesktopLoginError::local("Too many pending login attempts"));
}
let challenge_id = generate_random_uuid();
pending.insert(
challenge_id.clone(),
PendingChallenge {
device_token: created.device_token,
expires_at: created.expires_at,
client,
},
);
Ok(DesktopLoginChallenge {
challenge_id,
verification_url: created.verification_url,
confirmation_code: created.confirmation_code,
expires_at: created.expires_at,
poll_interval_seconds: created.poll_interval_seconds.max(5),
})
}
pub(super) async fn poll_challenge(
state: &DesktopLoginBridgeState,
manager: &StorytellerCredentialManager,
jar: &Arc<CookieStoreMutex>,
challenge_id: &str,
) -> Result<DesktopLoginOutcome, DesktopLoginError> {
let challenge = {
let mut pending = state.pending.lock().await;
let challenge = pending.get(challenge_id).cloned().ok_or_else(|| {
DesktopLoginError::local("Login attempt was cancelled or is no longer available")
})?;
if challenge.expires_at <= Utc::now() {
pending.remove(challenge_id);
return Ok(expired());
}
challenge
};
let origin = challenge.client.api_origin();
let polled = challenge
.client
.poll(&challenge.device_token)
.await
.map_err(|e| DesktopLoginError::from_client(&origin, e))?;
if !polled.response.success || polled.response.status == LoginChallengeState::Unknown {
return Err(DesktopLoginError::local("Unrecognized login response"));
}
if polled.response.status != LoginChallengeState::Redeemed {
if polled.response.status == LoginChallengeState::Failed {
state.pending.lock().await.remove(challenge_id);
}
return Ok(DesktopLoginOutcome {
status: polled.response.status,
maybe_failure_type: polled.response.maybe_failure_type,
maybe_user: None,
});
}
let signed = polled
.response
.maybe_signed_session
.ok_or_else(|| DesktopLoginError::local("Login server did not issue a session"))?;
let set_cookie = polled
.session_set_cookie
.ok_or_else(|| DesktopLoginError::local("Login server did not set a session cookie"))?;
let (cookie, user) = verify_session(&challenge.client, &signed, set_cookie).await?;
{
let pending = state.pending.lock().await;
// A cancellation during either HTTP request must prevent local installation.
if !pending.contains_key(challenge_id) {
return Err(DesktopLoginError::local("Login attempt was cancelled"));
}
if challenge.expires_at <= Utc::now() {
return Ok(expired());
}
install_session_cookie(&challenge.client, &signed, cookie, manager, jar)?;
}
// Keep the challenge for idempotent IPC retries; it expires on its original deadline.
persist_session_cookie(jar).await?;
info!("Website login complete: origin={}", origin);
Ok(DesktopLoginOutcome {
status: LoginChallengeState::Redeemed,
maybe_failure_type: None,
maybe_user: Some(user),
})
}
pub(super) async fn cancel_challenge(state: &DesktopLoginBridgeState, challenge_id: &str) {
state.pending.lock().await.remove(challenge_id);
}
async fn verify_session(
client: &LoginChallengeClient,
signed: &str,
set_cookie: String,
) -> Result<(RawCookie<'static>, SessionUserInfo), DesktopLoginError> {
let cookie = RawCookie::parse(set_cookie)
.map_err(|_| DesktopLoginError::local("Invalid session cookie"))?
.into_owned();
if cookie.name() != "session" || cookie.value() != signed {
return Err(DesktopLoginError::local(
"Session cookie did not match the redeemed session",
));
}
// Validate on the SAME native API host before publishing any new credentials.
let session = client
.session(&signed)
.await
.map_err(|e| DesktopLoginError::from_client(&client.api_origin(), e))?;
let user = session
.user
.filter(|_| session.success && session.logged_in)
.ok_or_else(|| DesktopLoginError::local("The redeemed session could not authenticate"))?;
Ok((cookie, user))
}
fn install_session_cookie(
client: &LoginChallengeClient,
signed: &str,
cookie: RawCookie<'static>,
manager: &StorytellerCredentialManager,
jar: &Arc<CookieStoreMutex>,
) -> Result<(), DesktopLoginError> {
let mut store = jar
.store
.lock()
.map_err(|_| DesktopLoginError::local("HTTP cookie store unavailable"))?;
let mut candidate = store.clone();
candidate.store_response_cookies([cookie].into_iter(), &client.api_url());
let credentials = get_credentials_from_cookie_store(&candidate, &client.api_url())
.map_err(|_| DesktopLoginError::local("Unable to read session cookie"))?;
if credentials.session.as_ref().map(|c| c.as_str()) != Some(signed) {
return Err(DesktopLoginError::local(
"Session cookie does not apply to the configured API host",
));
}
manager
.set_credentials(&credentials)
.map_err(|_| DesktopLoginError::local("Unable to store native login credentials"))?;
*store = candidate;
Ok(())
}
async fn persist_session_cookie(jar: &Arc<CookieStoreMutex>) -> Result<(), DesktopLoginError> {
let saved = jar
.request_save()
.map_err(|_| DesktopLoginError::local("Unable to persist login cookie"))?;
tokio::task::spawn_blocking(move || saved.recv())
.await
.map_err(|_| DesktopLoginError::local("Unable to persist login cookie"))?
.map_err(|_| DesktopLoginError::local("Unable to persist login cookie"))?;
Ok(())
}
fn expired() -> DesktopLoginOutcome {
DesktopLoginOutcome {
status: LoginChallengeState::Failed,
maybe_failure_type: Some(LoginChallengeFailure::Expired),
maybe_user: None,
}
}
#[cfg(test)]
#[path = "storyteller_login_bridge_tests.rs"]
mod login_bridge_tests;

View File

@ -2,4 +2,11 @@ pub mod storyteller_purge_credentials_command;
pub mod storyteller_get_credits_command;
pub mod storyteller_get_subscription_command;
pub mod stripe_checkout;
pub mod stripe_customer_portal;
pub mod stripe_customer_portal;
pub(crate) mod login_bridge;
pub mod storyteller_cancel_login_challenge_command;
pub mod storyteller_create_login_challenge_command;
pub mod storyteller_get_login_session_command;
pub mod storyteller_password_login_command;
pub mod storyteller_password_signup_command;
pub mod storyteller_poll_login_challenge_command;

View File

@ -0,0 +1,14 @@
use tauri::State;
use crate::services::storyteller::commands::login_bridge::{
cancel_challenge, DesktopLoginBridgeState, DesktopLoginError,
};
#[tauri::command]
pub async fn storyteller_cancel_login_challenge_command(
state: State<'_, DesktopLoginBridgeState>,
challenge_id: String,
) -> Result<(), DesktopLoginError> {
cancel_challenge(&state, &challenge_id).await;
Ok(())
}

View File

@ -0,0 +1,14 @@
use tauri::State;
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::services::storyteller::commands::login_bridge::{
begin_challenge, DesktopLoginBridgeState, DesktopLoginChallenge, DesktopLoginError,
};
#[tauri::command]
pub async fn storyteller_create_login_challenge_command(
config: State<'_, AppEnvConfigs>,
state: State<'_, DesktopLoginBridgeState>,
) -> Result<DesktopLoginChallenge, DesktopLoginError> {
begin_challenge(&config.storyteller_host, &state).await
}

View File

@ -0,0 +1,19 @@
use artcraft_api_defs::users::session_info::SessionUserInfo;
use artcraft_client::utils::login_challenge_client::LoginChallengeClient;
use tauri::{AppHandle, State};
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::services::storyteller::commands::login_bridge::{
current_login_session, http_cookie_jar, DesktopLoginError,
};
#[tauri::command]
pub async fn storyteller_get_login_session_command(
app: AppHandle,
config: State<'_, AppEnvConfigs>,
) -> Result<Option<SessionUserInfo>, DesktopLoginError> {
let client = LoginChallengeClient::new(&config.storyteller_host).map_err(|error| {
DesktopLoginError::from_client(&config.storyteller_host.to_api_hostname_and_scheme(), error)
})?;
current_login_session(&client, &http_cookie_jar(&app)?).await
}

View File

@ -0,0 +1,436 @@
//! Commands' native implementation + real ArtCraft bindings + loopback HTTP.
//! All listeners bind to an ephemeral local port; no production host is contacted.
use super::*;
use crate::core::state::data_dir::app_data_root::AppDataRoot;
use artcraft_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
use serde_json::{json, Value};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::thread;
use std::time::Duration;
use tauri_plugin_http::reqwest_cookie_store::CookieStore;
const SIGNED: &str = "signed_native_session_fixture";
const DEVICE: &str = "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD";
#[tokio::test]
async fn approved_session_is_verified_installed_persisted_and_retried_entirely_in_rust() {
let server = server(vec![
create(),
pending(),
redeemed(),
session(),
redeemed(),
session(),
]);
let h = harness();
// Native installation must preserve visitor cookies and avoid importing other origins.
h.jar.store.lock().unwrap().store_response_cookies(
[RawCookie::parse("visitor=existing; Path=/; Max-Age=3600")
.unwrap()
.into_owned()]
.into_iter(),
&server_url(&server),
);
h.manager
.set_credentials(&StorytellerCredentialSet::initialize_with_just_avt(
StorytellerAvtCookie::new("existing".into()),
))
.unwrap();
let created = begin_challenge(&server.host, &h.state).await.unwrap();
let public = serde_json::to_string(&created).unwrap();
assert!(!public.contains(DEVICE));
assert!(!public.contains("device_token"));
assert!(h
.manager
.get_credentials_required()
.unwrap()
.session
.is_none());
let wait = poll_challenge(&h.state, &h.manager, &h.jar, &created.challenge_id)
.await
.unwrap();
assert_eq!(wait.status, LoginChallengeState::Pending);
assert!(h
.manager
.get_credentials_required()
.unwrap()
.session
.is_none());
for _ in 0..2 {
let result = poll_challenge(&h.state, &h.manager, &h.jar, &created.challenge_id)
.await
.unwrap();
assert_eq!(result.status, LoginChallengeState::Redeemed);
assert_eq!(result.maybe_user.as_ref().unwrap().username, "google_user");
// This was the real failure: use_qt exists on the server, not this desktop.
let flags = &result.maybe_user.as_ref().unwrap().maybe_feature_flags;
assert_eq!(flags.len(), 1);
assert_eq!(flags.first().unwrap().to_str(), "studio");
assert!(!serde_json::to_string(&result).unwrap().contains(SIGNED));
let credentials = h.manager.get_credentials_required().unwrap();
assert_eq!(credentials.session.unwrap().as_str(), SIGNED);
assert_eq!(credentials.avt.unwrap().as_str(), "existing");
assert!(std::fs::read_to_string(&h.jar.path)
.unwrap()
.contains(SIGNED));
}
server.thread.join().unwrap();
}
#[tokio::test]
async fn rejection_and_timeout_never_install_a_session() {
for expired in [false, true] {
let mut steps = vec![create()];
if !expired {
steps.push(step(
"/v1/login_challenges/poll",
json!({"success":true,"status":"failed","maybe_failure_type":"user_declined"}),
));
}
let server = server(steps);
let h = harness();
let created = begin_challenge(&server.host, &h.state).await.unwrap();
if expired {
h.state
.pending
.lock()
.await
.get_mut(&created.challenge_id)
.unwrap()
.expires_at = Utc::now();
}
let result = poll_challenge(&h.state, &h.manager, &h.jar, &created.challenge_id)
.await
.unwrap();
assert_eq!(result.status, LoginChallengeState::Failed);
assert_eq!(
result.maybe_failure_type,
Some(if expired {
LoginChallengeFailure::Expired
} else {
LoginChallengeFailure::UserDeclined
})
);
assert!(h.manager.get_credentials().unwrap().is_none());
assert!(h
.jar
.store
.lock()
.unwrap()
.iter_unexpired()
.next()
.is_none());
server.thread.join().unwrap();
}
}
#[tokio::test]
async fn invalid_downstream_session_is_not_installed_and_error_has_host_without_credentials() {
let mut invalid = session();
invalid.status = 401;
invalid.body = json!({"echo": SIGNED});
let server = server(vec![create(), redeemed(), invalid]);
let h = harness();
let created = begin_challenge(&server.host, &h.state).await.unwrap();
let error = poll_challenge(&h.state, &h.manager, &h.jar, &created.challenge_id)
.await
.err()
.unwrap();
assert_eq!(error.status, Some(401));
assert!(!error.retryable);
assert!(error
.message
.contains(&server.host.to_api_hostname_and_scheme()));
assert!(!format!("{error:?}").contains(SIGNED));
assert!(h.manager.get_credentials().unwrap().is_none());
assert!(h
.jar
.store
.lock()
.unwrap()
.iter_unexpired()
.next()
.is_none());
server.thread.join().unwrap();
}
#[tokio::test]
async fn cancelling_during_http_prevents_late_cookie_installation() {
let mut delayed = redeemed();
delayed.delay = Duration::from_millis(150);
let server = server(vec![create(), delayed, session()]);
let h = harness();
let created = begin_challenge(&server.host, &h.state).await.unwrap();
let (result, _) = tokio::join!(
poll_challenge(&h.state, &h.manager, &h.jar, &created.challenge_id),
async {
tokio::time::sleep(Duration::from_millis(30)).await;
cancel_challenge(&h.state, &created.challenge_id).await;
}
);
assert!(result.is_err());
assert!(h.manager.get_credentials().unwrap().is_none());
assert!(h
.jar
.store
.lock()
.unwrap()
.iter_unexpired()
.next()
.is_none());
server.thread.join().unwrap();
}
#[tokio::test]
async fn unknown_states_and_redirects_fail_closed() {
for redirect in [false, true] {
let mut result = step(
"/v1/login_challenges/poll",
json!({"success":true,"status":"future_state","maybe_signed_session":SIGNED}),
);
if redirect {
result.status = 302;
result.headers = "Location: https://must-never-be-contacted.invalid/\r\n".into();
}
let server = server(vec![create(), result]);
let h = harness();
let created = begin_challenge(&server.host, &h.state).await.unwrap();
let error = poll_challenge(&h.state, &h.manager, &h.jar, &created.challenge_id)
.await
.err()
.unwrap();
assert!(!error.retryable);
if redirect {
assert_eq!(error.status, Some(302));
}
assert!(h.manager.get_credentials().unwrap().is_none());
server.thread.join().unwrap();
}
}
#[test]
fn website_origin_must_match_native_api_environment() {
let local = LoginChallengeClient::new(&ApiHost::Localhost { port: 12345 }).unwrap();
let prod = LoginChallengeClient::new(&ApiHost::Storyteller).unwrap();
let fragment = format!("#approval_token={}", "A".repeat(43));
assert!(local.allows_verification_url(&format!("http://localhost:4201/login/desktop{fragment}")));
assert!(!local.allows_verification_url(&format!(
"https://app.getartcraft.com/login/desktop{fragment}"
)));
assert!(prod.allows_verification_url(&format!(
"https://app.getartcraft.com/login/desktop{fragment}"
)));
assert!(!prod.allows_verification_url(&format!("http://localhost:4201/login/desktop{fragment}")));
}
#[tokio::test]
async fn malformed_session_data_still_cannot_install_credentials() {
for (field, value) in [("maybe_feature_flags", json!([42])), ("username", Value::Null)] {
let mut invalid = session();
invalid.body["user"][field] = value;
let server = server(vec![create(), redeemed(), invalid]);
let h = harness();
let created = begin_challenge(&server.host, &h.state).await.unwrap();
assert!(poll_challenge(&h.state, &h.manager, &h.jar, &created.challenge_id).await.is_err());
assert!(h.manager.get_credentials().unwrap().is_none());
assert!(h.jar.store.lock().unwrap().iter_unexpired().next().is_none());
server.thread.join().unwrap();
}
}
#[tokio::test]
async fn password_login_and_signup_verify_persist_and_recheck_via_native_api() {
for signup in [false, true] {
let mut auth = redeemed();
auth.path = if signup { "/v1/create_account" } else { "/v1/login" };
auth.body = json!({"success":true,"signed_session":SIGNED});
let server = server(vec![auth, session(), session()]);
let h = harness();
let (login, signup) = if signup {
(None, Some(PasswordSignupRequest { username: "google_user".into(), email_address: "user@example.test".into(), password: "fixture_password".into(), password_confirmation: "fixture_password".into(), signup_source: "artcraft".into() }))
} else {
(Some(PasswordLoginRequest { username_or_email: "google_user".into(), password: "fixture_password".into() }), None)
};
let user = password_auth(&server.host, &h.manager, &h.jar, login, signup).await.unwrap();
assert_eq!(user.username, "google_user");
assert_eq!(h.manager.get_credentials_required().unwrap().session.unwrap().as_str(), SIGNED);
assert!(std::fs::read_to_string(&h.jar.path).unwrap().contains(SIGNED));
let client = LoginChallengeClient::new(&server.host).unwrap();
assert_eq!(current_login_session(&client, &h.jar).await.unwrap().unwrap().username, "google_user");
server.thread.join().unwrap();
}
}
#[tokio::test]
async fn empty_native_cookie_jar_needs_no_session_http_request() {
let h = harness();
let client = LoginChallengeClient::new(&ApiHost::Localhost { port: 1 }).unwrap();
assert!(current_login_session(&client, &h.jar).await.unwrap().is_none());
}
struct Harness {
_directory: tempfile::TempDir,
state: DesktopLoginBridgeState,
manager: StorytellerCredentialManager,
jar: Arc<CookieStoreMutex>,
}
struct Server {
host: ApiHost,
thread: thread::JoinHandle<()>,
}
struct Step {
path: &'static str,
status: u16,
body: Value,
headers: String,
delay: Duration,
}
fn harness() -> Harness {
let directory = tempfile::tempdir().unwrap();
let root = AppDataRoot::create_existing(directory.path()).unwrap();
let manager = StorytellerCredentialManager::initialize_empty(&root);
let jar = Arc::new(CookieStoreMutex::new(
directory.path().join("cookies.json"),
CookieStore::default(),
));
Harness {
_directory: directory,
state: DesktopLoginBridgeState::default(),
manager,
jar,
}
}
fn server_url(server: &Server) -> reqwest::Url {
reqwest::Url::parse(&format!("{}/", server.host.to_api_hostname_and_scheme())).unwrap()
}
fn server(steps: Vec<Step>) -> Server {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let thread = thread::spawn(move || {
for step in steps {
let (mut stream, _) = listener.accept().unwrap();
stream
.set_read_timeout(Some(Duration::from_secs(10)))
.unwrap();
let mut data = Vec::new();
let mut buffer = [0; 4096];
loop {
let count = stream.read(&mut buffer).unwrap();
assert!(count > 0);
data.extend_from_slice(&buffer[..count]);
if let Some(end) = data.windows(4).position(|v| v == b"\r\n\r\n") {
let headers = String::from_utf8_lossy(&data[..end]).to_lowercase();
let length: usize = headers
.lines()
.find_map(|s| s.strip_prefix("content-length:"))
.map(|s| s.trim().parse().unwrap())
.unwrap_or(0);
if data.len() >= end + 4 + length {
break;
}
}
}
let request = String::from_utf8(data).unwrap();
assert_eq!(request.split_whitespace().nth(1), Some(step.path));
assert!(request
.to_lowercase()
.contains(&format!("host: localhost:{port}")));
if step.path == "/v1/session" {
assert!(request.starts_with("GET "));
assert!(request.contains(&format!("session={SIGNED}")));
} else {
assert!(request.starts_with("POST "));
assert!(!request.to_lowercase().contains("cookie:"));
if step.path.ends_with("/poll") {
let body: Value =
serde_json::from_str(request.split_once("\r\n\r\n").unwrap().1).unwrap();
assert_eq!(body, json!({"device_token":DEVICE}));
}
}
thread::sleep(step.delay);
let body = step.body.to_string();
write!(stream, "HTTP/1.1 {} Test\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{}\r\n{}", step.status, body.len(), step.headers, body).unwrap();
}
});
Server {
host: ApiHost::Localhost { port: port.into() },
thread,
}
}
fn step(path: &'static str, body: Value) -> Step {
Step {
path,
body,
status: 200,
headers: String::new(),
delay: Duration::ZERO,
}
}
fn create() -> Step {
step(
"/v1/login_challenges/create",
json!({"success":true,"device_token":DEVICE,"verification_url":format!("http://localhost:4201/login/desktop#approval_token={}","A".repeat(43)),"confirmation_code":"WDJBMJHT","expires_at":Utc::now()+chrono::Duration::minutes(20),"poll_interval_seconds":5}),
)
}
fn pending() -> Step {
step(
"/v1/login_challenges/poll",
json!({"success":true,"status":"pending","maybe_failure_type":null}),
)
}
fn redeemed() -> Step {
let mut response = step(
"/v1/login_challenges/poll",
json!({"success":true,"status":"redeemed","maybe_failure_type":null,"maybe_signed_session":SIGNED}),
);
response.headers = format!("Set-Cookie: session={SIGNED}; HttpOnly; Path=/; Max-Age=3600\r\n");
response
}
fn session() -> Step {
let mut user = json!({
"user_token":"u_native_test", "username":"google_user", "display_name":"Google User", "email_gravatar_hash":"fixture",
"core_info":{"user_token":"u_native_test","username":"google_user","display_name":"Google User","gravatar_hash":"fixture","default_avatar":{"image_index":1,"color_index":1}},
"onboarding":{"email_not_set":false,"email_not_confirmed":false,"password_not_set":true,"username_not_customized":false},
"maybe_feature_flags":["studio", "use_qt", "future_server_flag"],"fakeyou_plan":"free","storyteller_stream_plan":"free"
});
for field in [
"can_access_studio",
"can_use_tts",
"can_use_w2l",
"can_delete_own_tts_results",
"can_delete_own_w2l_results",
"can_delete_own_account",
"can_upload_tts_models",
"can_upload_w2l_templates",
"can_delete_own_tts_models",
"can_delete_own_w2l_templates",
"can_approve_w2l_templates",
"can_edit_other_users_profiles",
"can_edit_other_users_tts_models",
"can_edit_other_users_w2l_templates",
"can_delete_other_users_tts_models",
"can_delete_other_users_w2l_templates",
"can_delete_other_users_tts_results",
"can_delete_other_users_w2l_results",
"can_ban_users",
"can_delete_users",
] {
user[field] = json!(false);
}
step(
"/v1/session",
json!({"success":true,"logged_in":true,"user":user}),
)
}

View File

@ -0,0 +1,26 @@
use artcraft_api_defs::users::session_info::SessionUserInfo;
use artcraft_client::endpoints::users::password_login::PasswordLoginRequest;
use tauri::{AppHandle, State};
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::services::storyteller::commands::login_bridge::{
http_cookie_jar, password_auth, DesktopLoginError,
};
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
#[tauri::command]
pub async fn storyteller_password_login_command(
app: AppHandle,
config: State<'_, AppEnvConfigs>,
manager: State<'_, StorytellerCredentialManager>,
request: PasswordLoginRequest,
) -> Result<SessionUserInfo, DesktopLoginError> {
password_auth(
&config.storyteller_host,
&manager,
&http_cookie_jar(&app)?,
Some(request),
None,
)
.await
}

View File

@ -0,0 +1,26 @@
use artcraft_api_defs::users::session_info::SessionUserInfo;
use artcraft_client::endpoints::users::password_signup::PasswordSignupRequest;
use tauri::{AppHandle, State};
use crate::core::state::app_env_configs::app_env_configs::AppEnvConfigs;
use crate::services::storyteller::commands::login_bridge::{
http_cookie_jar, password_auth, DesktopLoginError,
};
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
#[tauri::command]
pub async fn storyteller_password_signup_command(
app: AppHandle,
config: State<'_, AppEnvConfigs>,
manager: State<'_, StorytellerCredentialManager>,
request: PasswordSignupRequest,
) -> Result<SessionUserInfo, DesktopLoginError> {
password_auth(
&config.storyteller_host,
&manager,
&http_cookie_jar(&app)?,
None,
Some(request),
)
.await
}

View File

@ -0,0 +1,17 @@
use tauri::{AppHandle, State};
use crate::services::storyteller::commands::login_bridge::{
http_cookie_jar, poll_challenge, DesktopLoginBridgeState, DesktopLoginError, DesktopLoginOutcome,
};
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
#[tauri::command]
pub async fn storyteller_poll_login_challenge_command(
app: AppHandle,
state: State<'_, DesktopLoginBridgeState>,
manager: State<'_, StorytellerCredentialManager>,
challenge_id: String,
) -> Result<DesktopLoginOutcome, DesktopLoginError> {
let jar = http_cookie_jar(&app)?;
poll_challenge(&state, &manager, &jar, &challenge_id).await
}

View File

@ -3,9 +3,10 @@ use crate::core::state::artcraft_platform_info::ArtcraftPlatformInfo;
use crate::core::state::artcraft_usage_tracker::artcraft_usage_tracker::ArtcraftUsageTracker;
use crate::services::storyteller::state::storyteller_credential_manager::StorytellerCredentialManager;
use anyhow::anyhow;
use artcraft_api_defs::analytics::log_active_user::LogAppActiveUserRequest;
use artcraft_api_defs::analytics::log_active_user::{LogAppActiveUserRequest, LOG_ACTIVE_USER_V2_PATH};
use artcraft_client::endpoints::analytics::log_active_user_v2::log_active_user_v2;
use artcraft_client::error::api_error::ApiError;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
use artcraft_client::error::storyteller_error::StorytellerError;
use errors::AnyhowResult;
use log::{debug, error, info};
@ -38,7 +39,7 @@ pub async fn storyteller_activity_thread(
&app_session_token,
).await;
if let Err(err) = res {
error!("An error occurred: {:?}", err);
error!("Activity request failed: origin={} path={} error={:?}", app_env_configs.storyteller_host.to_api_hostname_and_scheme(), LOG_ACTIVE_USER_V2_PATH, err);
}
// NB: Sleep if an error occurs.
tokio::time::sleep(std::time::Duration::from_millis(ERROR_SLEEP_MILLIS)).await;
@ -62,7 +63,7 @@ async fn polling_loop(
continue;
}
Some(creds) => {
if creds.is_empty() {
if !has_activity_session(&creds) {
tokio::time::sleep(std::time::Duration::from_millis(5_000)).await;
continue;
}
@ -123,7 +124,31 @@ async fn polling_loop(
};
// Wait at least a minute, no matter what the server tells us.
let wait_millis = std::cmp::min(wait_millis, 60_000);
let wait_millis = std::cmp::max(wait_millis, 60_000);
tokio::time::sleep(std::time::Duration::from_millis(wait_millis)).await;
}
}
// Anonymous visitor tracking is not authentication for active_user_v2.
fn has_activity_session(creds: &StorytellerCredentialSet) -> bool {
creds.session.as_ref().map(|session| !session.as_str().is_empty()).unwrap_or(false)
}
#[cfg(test)]
mod login_bridge_tests {
use super::has_activity_session;
use artcraft_client::credentials::storyteller_credential_set::StorytellerCredentialSet;
use artcraft_client::credentials::storyteller_avt_cookie::StorytellerAvtCookie;
use artcraft_client::credentials::storyteller_session_cookie::StorytellerSessionCookie;
#[test]
fn anonymous_visitor_cookie_does_not_authorize_activity_requests() {
assert!(!has_activity_session(&StorytellerCredentialSet::empty()));
let visitor_only = StorytellerCredentialSet::initialize_with_just_avt(StorytellerAvtCookie::new("visitor_fixture".into()));
assert!(!has_activity_session(&visitor_only));
let empty_session = StorytellerCredentialSet::initialize_with_just_cookie(StorytellerSessionCookie::new(String::new()));
assert!(!has_activity_session(&empty_session));
let signed_in = StorytellerCredentialSet::initialize_with_just_cookie(StorytellerSessionCookie::new("signed_session_fixture".into()));
assert!(has_activity_session(&signed_in));
}
}

View File

@ -1,4 +1,4 @@
/// The version of the ArtCraft desktop app reported in the UI and via Analytics.
/// This should match the CI builds.
pub const ARTCRAFT_VERSION: &str = "0.39.0";
pub const ARTCRAFT_VERSION: &str = "0.41.0";

View File

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2.0.0-rc",
"productName": "ArtCraft",
"version": "0.39.0",
"version": "0.41.0",
"identifier": "ai.artcraft.app",
"build": {
"frontendDist": "../../../frontend/apps/artcraft/dist",

View File

@ -1,7 +1,7 @@
{
"$schema": "https://schema.tauri.app/config/2.0.0-rc",
"productName": "ArtCraft",
"version": "0.39.0",
"version": "0.41.0",
"identifier": "ai.artcraft.app",
"build": {
"frontendDist": "../../../frontend/apps/artcraft/dist",

View File

@ -0,0 +1,17 @@
[package]
name = "artcraft_client_identity"
edition = "2024"
version = "0.0.1"
publish = false
[lib]
name = "artcraft_client_identity"
path = "src/lib.rs"
[dependencies]
# External
url.workspace = true
[dev-dependencies]
# (None)

View File

@ -0,0 +1,166 @@
use url::{Host, Url};
use crate::origins::{ARTCRAFT_DESKTOP_DEVELOPMENT_ORIGIN, ARTCRAFT_DESKTOP_ORIGIN};
use crate::third_party_provider::{ThirdPartyProvider, THIRD_PARTY_PROVIDERS};
/// Hostnames of our deployed APIs (HTTPS only).
const ARTCRAFT_API_HOSTNAMES: [&str; 3] = [
"api.storyteller.ai",
"api.getartcraft.com",
"api.fakeyou.com",
];
/// Domains we own. Subdomains match too (CDNs, uploads, websites).
const ARTCRAFT_DOMAINS: [&str; 4] = [
"storyteller.ai",
"getartcraft.com",
"fakeyou.com",
"artcraft.ai",
];
/// Who a request is going to, which decides how the desktop app identifies itself.
#[derive(Debug, PartialEq, Eq)]
pub enum Destination {
/// Our HTTP API, deployed or running locally, and the `Origin` to declare to it.
ArtcraftApi { origin: &'static str },
/// Our other hosts: CDNs, uploads, websites.
ArtcraftHost,
/// A known third-party provider.
ThirdParty(&'static ThirdPartyProvider),
/// Anything else.
Unknown,
}
impl Destination {
pub fn classify(destination: &Url) -> Self {
if is_local_development_api(destination) {
return Self::ArtcraftApi { origin: ARTCRAFT_DESKTOP_DEVELOPMENT_ORIGIN };
}
let Some(host) = destination.host_str() else {
return Self::Unknown;
};
if destination.scheme() == "https" && ARTCRAFT_API_HOSTNAMES.contains(&host) {
return Self::ArtcraftApi { origin: ARTCRAFT_DESKTOP_ORIGIN };
}
if ARTCRAFT_DOMAINS.iter().any(|domain| is_domain_or_subdomain(host, domain)) {
return Self::ArtcraftHost;
}
THIRD_PARTY_PROVIDERS
.iter()
.find(|provider| provider.domains.iter().any(|domain| is_domain_or_subdomain(host, domain)))
.map_or(Self::Unknown, Self::ThirdParty)
}
}
fn is_local_development_api(destination: &Url) -> bool {
if !matches!(destination.scheme(), "http" | "https") {
return false;
}
match destination.host() {
Some(Host::Domain("localhost")) => true,
Some(Host::Ipv4(address)) => address.is_loopback(),
Some(Host::Ipv6(address)) => address.is_loopback(),
_ => false,
}
}
fn is_domain_or_subdomain(host: &str, domain: &str) -> bool {
host == domain
|| host
.strip_suffix(domain)
.is_some_and(|prefix| prefix.ends_with('.'))
}
#[cfg(test)]
mod tests {
use super::*;
mod artcraft {
use super::*;
#[test]
fn deployed_apis_get_desktop_origin() {
for destination in [
"https://api.storyteller.ai/v1/session",
"https://api.getartcraft.com/v1/session",
"https://api.fakeyou.com/v1/session",
] {
assert_eq!(classify(destination), Destination::ArtcraftApi { origin: "https://desktop.getartcraft.com" });
}
}
#[test]
fn local_apis_get_development_origin() {
for destination in [
"http://localhost:12345/v1/session",
"https://localhost:12345/v1/session",
"http://127.0.0.1:12345/v1/session",
"http://[::1]:12345/v1/session",
] {
assert_eq!(classify(destination), Destination::ArtcraftApi { origin: "http://localhost" });
}
}
#[test]
fn other_owned_hosts_are_not_apis() {
for destination in [
"https://cdn-2.fakeyou.com/media/a/b.png",
"https://cdn.storyteller.ai/media/a/b.png",
"https://style.storyteller.ai/",
"https://app.getartcraft.com/",
"https://getartcraft.com/",
"http://api.storyteller.ai/v1/session",
] {
assert_eq!(classify(destination), Destination::ArtcraftHost, "{destination}");
}
}
}
mod third_party {
use super::*;
#[test]
fn providers_get_their_own_origins() {
for (destination, name, origin) in [
("https://grok.com/rest/app-chat/conversations/new", "Grok", "https://grok.com"),
("https://assets.grok.com/users/a/b.mp4", "Grok", "https://grok.com"),
("https://imagine-public.x.ai/a.png", "Grok", "https://grok.com"),
("https://www.midjourney.com/api/submit-jobs", "Midjourney", "https://www.midjourney.com"),
("https://cdn.midjourney.com/a/0_0.png", "Midjourney", "https://www.midjourney.com"),
("https://sora.chatgpt.com/backend/nf/create", "Sora", "https://sora.chatgpt.com"),
("https://videos.openai.com/a.mp4", "Sora", "https://sora.chatgpt.com"),
("https://chatgpt.com/backend-api/sentinel", "ChatGPT", "https://chatgpt.com"),
("https://api.worldlabs.ai/api/v1/worlds", "World Labs", "https://marble.worldlabs.ai"),
("https://static.kinovi.ai/a.png", "Kinovi", "https://kinovi.ai"),
("https://static.seedance2-pro.com/materials/a.png", "Seedance 2 Pro", "https://seedance2-pro.com"),
("https://v3b.fal.media/files/a.png", "fal", "https://fal.ai"),
("https://console.gmicloud.ai/api", "GMI Cloud", "https://console.gmicloud.ai"),
] {
let Destination::ThirdParty(provider) = classify(destination) else {
panic!("{destination} is not a third party");
};
assert_eq!((provider.name, provider.origin), (name, origin));
}
}
#[test]
fn lookalikes_and_others_are_unknown() {
for destination in [
"https://api.storyteller.ai.example.com/v1/session",
"https://notstoryteller.ai/",
"https://evilgrok.com/",
"https://grok.com.example.com/",
"https://www.gravatar.com/avatar/a",
"https://storage.googleapis.com/bucket/a.png",
"http://192.168.1.2:12345/v1/session",
"tauri://localhost",
] {
assert_eq!(classify(destination), Destination::Unknown, "{destination}");
}
}
}
fn classify(destination: &str) -> Destination {
Destination::classify(&Url::parse(destination).unwrap())
}
}

View File

@ -0,0 +1,12 @@
//! artcraft_client_identity
//!
//! How the ArtCraft desktop app identifies itself (`Origin`, `User-Agent`) to each destination.
//!
//! Our own APIs get the declared ArtCraft desktop identity. Known third-party providers get an
//! identity close to their own website, and never ours. The native third-party Rust clients
//! (Grok, Midjourney, Sora, etc.) set their own headers and do not use this crate.
pub mod destination;
pub mod origins;
pub mod third_party_provider;
pub mod user_agents;

View File

@ -0,0 +1,11 @@
/// `Origin` sent to our deployed APIs.
/// Keep in sync with `actix_cors_configs/src/configs/artcraft_desktop.rs` in artcraft-services.
pub const ARTCRAFT_DESKTOP_ORIGIN: &str = "https://desktop.getartcraft.com";
/// `Origin` sent to a locally running API (eg. `http://localhost:12345`).
/// Development CORS accepts any `localhost` origin.
pub const ARTCRAFT_DESKTOP_DEVELOPMENT_ORIGIN: &str = "http://localhost";
/// `Origin` packaged builds historically sent everywhere. Now only sent to our non-API hosts
/// (CDNs, websites), where it is left unchanged.
pub const LEGACY_DESKTOP_ORIGIN: &str = "https://studio.storyteller.ai";

View File

@ -0,0 +1,30 @@
/// A third-party provider, and the `Origin` of its own website that we present to its hosts.
#[derive(Debug, PartialEq, Eq)]
pub struct ThirdPartyProvider {
pub name: &'static str,
/// Registrable domains; subdomains match too.
pub domains: &'static [&'static str],
pub origin: &'static str,
}
/// Every third party that gets an invented origin. Origins match what each provider's native
/// Rust client already sends. First match wins, so more specific entries go first.
pub const THIRD_PARTY_PROVIDERS: [ThirdPartyProvider; 9] = [
ThirdPartyProvider { name: "Grok", domains: &["grok.com", "x.ai"], origin: "https://grok.com" },
ThirdPartyProvider { name: "Midjourney", domains: &["midjourney.com"], origin: "https://www.midjourney.com" },
ThirdPartyProvider {
name: "Sora",
domains: &["sora.chatgpt.com", "sora.com", "openai.com", "oaistatic.com"],
origin: "https://sora.chatgpt.com",
},
ThirdPartyProvider { name: "ChatGPT", domains: &["chatgpt.com"], origin: "https://chatgpt.com" },
ThirdPartyProvider {
name: "World Labs",
domains: &["worldlabs.ai", "wlt-ai.art"],
origin: "https://marble.worldlabs.ai",
},
ThirdPartyProvider { name: "Kinovi", domains: &["kinovi.ai"], origin: "https://kinovi.ai" },
ThirdPartyProvider { name: "Seedance 2 Pro", domains: &["seedance2-pro.com"], origin: "https://seedance2-pro.com" },
ThirdPartyProvider { name: "fal", domains: &["fal.ai", "fal.run", "fal.media"], origin: "https://fal.ai" },
ThirdPartyProvider { name: "GMI Cloud", domains: &["gmicloud.ai"], origin: "https://console.gmicloud.ai" },
];

View File

@ -0,0 +1,23 @@
/// `User-Agent` sent to our own APIs and hosts.
///
/// TODO: Change to "artcraft-desktop/1.0" once the backend services can parse it.
pub const ARTCRAFT_DESKTOP_USER_AGENT: &str = "storyteller-client/1.0";
/// `User-Agent` sent to third parties: the default of the OS webview Tauri runs on
/// (WKWebView on macOS, WebView2 on Windows, WebKitGTK on Linux).
///
/// NB: These are hardcoded snapshots and WILL go out of date as the OS webviews update
/// (especially WebView2's Chrome/Edge version, which auto-updates on Windows). Rust can't read
/// the webview's real `navigator.userAgent`, so refresh these periodically by checking
/// `navigator.userAgent` in the desktop app's devtools on each OS.
#[cfg(target_os = "macos")]
pub const WEBVIEW_USER_AGENT: &str =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
#[cfg(target_os = "windows")]
pub const WEBVIEW_USER_AGENT: &str =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36 Edg/140.0.0.0";
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub const WEBVIEW_USER_AGENT: &str =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko)";

View File

@ -36,6 +36,7 @@ urlpattern = "0.3"
regex = "1"
[dependencies]
artcraft_client_identity = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tauri = { workspace = true }

View File

@ -0,0 +1,207 @@
use artcraft_client_identity::destination::Destination;
use artcraft_client_identity::origins::LEGACY_DESKTOP_ORIGIN;
use artcraft_client_identity::user_agents::{ARTCRAFT_DESKTOP_USER_AGENT, WEBVIEW_USER_AGENT};
use http::{header, HeaderMap, HeaderValue};
use url::{Host, Url};
/// The `User-Agent` to send when the frontend didn't set one.
pub(crate) fn artcraft_default_user_agent(destination: &Url) -> &'static str {
match Destination::classify(destination) {
Destination::ArtcraftApi { .. } | Destination::ArtcraftHost => ARTCRAFT_DESKTOP_USER_AGENT,
Destination::ThirdParty(_) | Destination::Unknown => WEBVIEW_USER_AGENT,
}
}
/// Replace the webview's own `Origin` (packaged `tauri://localhost` etc., or a Vite loopback
/// origin at any port) with the identity chosen for the destination. The native HTTP bridge
/// shares the desktop cookie jar, so its identity must not depend on the webview.
pub(crate) fn normalize_artcraft_origin(destination: &Url, headers: &mut HeaderMap) {
let origin = headers.get(header::ORIGIN).and_then(|value| value.to_str().ok());
// Packaged-app webview origins on macOS and Windows.
let packaged_origin = headers.get(header::ORIGIN).is_none()
|| matches!(origin, Some("null" | "http://tauri.localhost" | "tauri://localhost"));
// Development webview origins (Vite on any loopback port).
let webview_origin = packaged_origin || origin.is_some_and(is_loopback_origin);
let replacement = match Destination::classify(destination) {
// Our APIs (deployed or local) see the declared desktop identity.
Destination::ArtcraftApi { origin } if webview_origin => origin,
// Known third parties see an origin close to their own website.
Destination::ThirdParty(provider) if webview_origin => provider.origin,
// Our CDNs and websites keep the historical packaged-app handling.
Destination::ArtcraftHost if packaged_origin => LEGACY_DESKTOP_ORIGIN,
// Unknown hosts and ordinary website origins are left untouched.
_ => return,
};
// HeaderMap is a multimap; insert replaces all existing Origin values.
headers.insert(header::ORIGIN, HeaderValue::from_static(replacement));
}
fn is_loopback_origin(origin: &str) -> bool {
let Ok(url) = Url::parse(origin) else {
return false;
};
if !matches!(url.scheme(), "http" | "https") {
return false;
}
match url.host() {
Some(Host::Domain("localhost")) => true,
Some(Host::Ipv4(address)) => address.is_loopback(),
Some(Host::Ipv6(address)) => address.is_loopback(),
_ => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
const API: &str = "https://api.storyteller.ai/v1/session";
const LOCAL_API: &str = "http://localhost:12345/v1/session";
const CDN: &str = "https://cdn-2.fakeyou.com/media/a/b.png";
const GCS: &str = "https://storage.googleapis.com/bucket/a.png";
const GROK: &str = "https://grok.com/rest/app-chat/conversations/new";
const MIDJOURNEY: &str = "https://www.midjourney.com/api/submit-jobs";
const UNKNOWN: &str = "https://www.gravatar.com/avatar/a";
const DEV_WEBVIEW_ORIGIN: &str = "http://127.0.0.1:5193";
const PACKAGED_ORIGINS: [Option<&str>; 4] =
[None, Some("null"), Some("http://tauri.localhost"), Some("tauri://localhost")];
mod development {
use super::*;
#[test]
fn normalizes_dynamic_ports_and_loopback_hosts() {
for origin in [
"http://127.0.0.1:5193",
"http://127.0.0.1:5194",
"http://127.0.0.1:65535",
"http://localhost:5173",
"http://[::1]:5193",
] {
assert_eq!(normalized(API, Some(origin)), "https://desktop.getartcraft.com");
assert_eq!(normalized(LOCAL_API, Some(origin)), "http://localhost");
assert_eq!(normalized(GROK, Some(origin)), "https://grok.com");
}
assert_eq!(
normalized("https://api.fakeyou.com/v1/session", Some(DEV_WEBVIEW_ORIGIN)),
"https://desktop.getartcraft.com"
);
}
#[test]
fn leaves_cdns_and_unknown_destinations_unchanged() {
for destination in [
CDN,
GCS,
UNKNOWN,
"https://api.storyteller.ai.example.com/v1/session",
"http://api.storyteller.ai/v1/session",
] {
assert_eq!(normalized(destination, Some(DEV_WEBVIEW_ORIGIN)), DEV_WEBVIEW_ORIGIN, "{destination}");
}
}
#[test]
fn leaves_non_webview_origins_unchanged() {
for origin in [
"https://app.getartcraft.com",
"https://example.com",
"http://localhost.example.com:5193",
"http://192.168.1.2:5193",
"not a URL",
"",
] {
assert_eq!(normalized(API, Some(origin)), origin);
assert_eq!(normalized(GROK, Some(origin)), origin);
}
}
}
mod packaged {
use super::*;
#[test]
fn our_apis_get_desktop_identity() {
for origin in PACKAGED_ORIGINS {
assert_eq!(normalized(API, origin), "https://desktop.getartcraft.com");
assert_eq!(normalized(LOCAL_API, origin), "http://localhost");
}
}
#[test]
fn third_parties_get_their_own_origin() {
for origin in PACKAGED_ORIGINS {
assert_eq!(normalized(GROK, origin), "https://grok.com");
assert_eq!(normalized(MIDJOURNEY, origin), "https://www.midjourney.com");
}
}
#[test]
fn cdns_keep_legacy_origin() {
for origin in PACKAGED_ORIGINS {
assert_eq!(normalized(CDN, origin), "https://studio.storyteller.ai");
}
}
#[test]
fn unknown_destinations_never_get_our_origin() {
for destination in [UNKNOWN, GCS] {
assert_eq!(normalized(destination, Some("tauri://localhost")), "tauri://localhost");
assert_eq!(normalized(destination, Some("null")), "null");
assert_eq!(normalized_or_missing(destination, None), None);
}
}
#[test]
fn replaces_duplicate_origin_values_without_changing_session_headers() {
let mut headers = HeaderMap::new();
headers.append(header::ORIGIN, HeaderValue::from_static(DEV_WEBVIEW_ORIGIN));
headers.append(header::ORIGIN, HeaderValue::from_static(DEV_WEBVIEW_ORIGIN));
headers.insert(header::COOKIE, HeaderValue::from_static("session=fixture"));
normalize_artcraft_origin(&Url::parse(API).unwrap(), &mut headers);
assert_eq!(headers.get_all(header::ORIGIN).iter().count(), 1);
assert_eq!(headers[header::ORIGIN], "https://desktop.getartcraft.com");
assert_eq!(headers[header::COOKIE], "session=fixture");
}
}
mod user_agent {
use super::*;
#[test]
fn ours_get_artcraft_user_agent() {
for destination in [API, LOCAL_API, CDN] {
assert_eq!(user_agent(destination), "storyteller-client/1.0");
}
}
#[test]
fn third_parties_get_webview_user_agent() {
for destination in [GROK, MIDJOURNEY, GCS, UNKNOWN] {
let user_agent = user_agent(destination);
assert!(user_agent.starts_with("Mozilla/5.0 ("), "{user_agent}");
assert!(!user_agent.contains("storyteller"), "{user_agent}");
}
}
fn user_agent(destination: &str) -> &'static str {
artcraft_default_user_agent(&Url::parse(destination).unwrap())
}
}
fn normalized(destination: &str, origin: Option<&str>) -> String {
normalized_or_missing(destination, origin).unwrap()
}
fn normalized_or_missing(destination: &str, origin: Option<&str>) -> Option<String> {
let mut headers = HeaderMap::new();
if let Some(origin) = origin {
headers.insert(header::ORIGIN, HeaderValue::from_str(origin).unwrap());
}
normalize_artcraft_origin(&Url::parse(destination).unwrap(), &mut headers);
headers.get(header::ORIGIN).map(|value| value.to_str().unwrap().to_owned())
}
}

View File

@ -16,12 +16,11 @@ use tauri::{
use tokio::sync::oneshot::{channel, Receiver, Sender};
use crate::{
artcraft_identity::{artcraft_default_user_agent, normalize_artcraft_origin},
scope::{Entry, Scope},
Error, Http, Result,
};
const HTTP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
struct ReqwestResponse(reqwest::Response);
impl tauri::Resource for ReqwestResponse {}
@ -269,7 +268,7 @@ pub async fn fetch<R: Runtime>(
builder = builder.cookie_provider(state.cookies_jar.clone());
}
let mut request = builder.build()?.request(method.clone(), url);
let mut request = builder.build()?.request(method.clone(), url.clone());
// POST and PUT requests should always have a 0 length content-length,
// if there is no body. https://fetch.spec.whatwg.org/#http-network-or-cache-fetch
@ -284,7 +283,7 @@ pub async fn fetch<R: Runtime>(
}
if !headers.contains_key(header::USER_AGENT) {
headers.append(header::USER_AGENT, HeaderValue::from_str(HTTP_USER_AGENT)?);
headers.append(header::USER_AGENT, HeaderValue::from_static(artcraft_default_user_agent(&url)));
}
// ensure we have an Origin header set
@ -305,26 +304,7 @@ pub async fn fetch<R: Runtime>(
headers.remove(header::ORIGIN);
};
// NB(bt): In production builds, the origin seems to be "null". This is what our server CORS filter sees:
// [2025-05-01T23:42:35Z WARN actix_cors_configs::configs::fakeyou] Invalid origin: "null"
// [2025-05-01T23:42:35Z WARN actix_cors_configs::util::netlify_branch_domain_matches] Invalid origin: "null"
// [2025-05-01T23:42:35Z WARN actix_cors_configs::util::netlify_branch_domain_matches] Invalid origin: "null"
// ...
// [2025-05-01T23:42:35Z WARN actix_cors_configs::util::netlify_branch_domain_matches] Invalid origin: "null"
// [2025-05-01T23:42:35Z INFO actix_web::middleware::logger] [storyteller-web-85f9b4974-ddvq7] IP=[redact]
// 939322e1095ee5e4-IAD "POST /v1/login HTTP/1.1" 400 42 "-" "tauri-plugin-http/2.4.3" 0.000076
let mut maybe_origin_header = headers.get(header::ORIGIN);
let replace_origin_header = maybe_origin_header.is_none()
|| maybe_origin_header == Some(&HeaderValue::from_static("null")) // Above error (Mac)
|| maybe_origin_header == Some(&HeaderValue::from_static("http://tauri.localhost")) // Windows
|| maybe_origin_header == Some(&HeaderValue::from_static("tauri://localhost")); // Mac plausibly causes this
if replace_origin_header {
// TODO(bt): Make this a sentinel origin, eg. sentinel.storyteller.ai.
// NB: HeadersMap is a multimap, but this should ensure we just have one value.
headers.insert(header::ORIGIN, HeaderValue::from_static("https://studio.storyteller.ai"));
}
normalize_artcraft_origin(&url, &mut headers);
if let Some(data) = data {
request = request.body(data);

View File

@ -12,6 +12,8 @@ use tauri::{
pub use error::{Error, Result};
mod artcraft_identity;
// NB(bt): We're making everything public so we can access it.
pub mod commands;
pub mod error;

View File

@ -0,0 +1,189 @@
# Desktop session regression — September 27, 2026
The combined development launcher (`92e6f438c3`, following the performance
change `df707bf8e1`) moved Vite from `localhost:5173` to an available port on
`127.0.0.1`. The vendored HTTP plugin forwarded that webview Origin to the
production API. The API rejected it with **400: Origin is not allowed to make
this request**.
The native login bridge and credits commands use a different HTTP transport and
continued working. Consequently the login modal correctly recognized the native
session, but Accounts, Library, and page media requests failed. Accounts treated
the error as logged out; its Log In button rechecked the valid native session
and immediately closed the login modal again.
The fix extends the existing packaged-desktop Origin normalization to loopback
development origins, at any port, for HTTPS requests to `api.storyteller.ai` and
`api.fakeyou.com`. Other development request destinations and non-loopback
website origins retain their headers. Cookie handling and API authorization are
unchanged. A frontend reload alone cannot update this fix: Rust must rebuild.
## Dedicated desktop origin and rollout
The desktop app now declares itself per destination. Both transports read the
values from one place, `crates/lib/artcraft_client_identity`
(`Destination::classify`, origins, user agents, third-party provider table):
| Destination | Origin sent | User-Agent |
|--------------------------------------------------------|-------------------------------------|--------------------------|
| Our APIs (`api.storyteller.ai`, `api.fakeyou.com`, …) | `https://desktop.getartcraft.com` | `storyteller-client/1.0` |
| Local API (`localhost`, `127.0.0.1`, `[::1]`) | `http://localhost` | `storyteller-client/1.0` |
| Our CDNs / sites (`*.storyteller.ai`, `*.fakeyou.com`) | unchanged (`studio.storyteller.ai`) | `storyteller-client/1.0` |
| Named third parties (`THIRD_PARTY_PROVIDERS`) | the provider's own site | OS webview |
| Any other host (incl. `storage.googleapis.com`) | webview origin, untouched | OS webview |
- The native Rust client (`artcraft_client`) sends the Origin and User-Agent on
every API request via `storyteller_client_builder`; it previously sent no
Origin.
- The "OS webview" User-Agents are hardcoded snapshots in
`artcraft_client_identity/src/user_agents.rs` and go out of date as the
webviews update (notably WebView2's Edge version on Windows). Refresh them
from `navigator.userAgent` in the desktop app's devtools on each OS.
- The vendored HTTP plugin only replaces the webview's own origin (packaged
`tauri://localhost` etc., or a loopback Vite origin), and only sets the
User-Agent when the frontend didn't.
- Native third-party Rust clients (Grok, Midjourney, Sora, World Labs, Kinovi)
set their own headers and are not affected.
- Older desktop releases keep working: the server still allows the studio and
Tauri origins, and requests without an Origin.
Keep the deployed origin in sync with
`../artcraft-services/crates/lib/actix_cors_configs/src/configs/artcraft_desktop.rs`.
Development servers accept any `localhost` origin.
Deploy the server allowlist to the APIs **before running or releasing a desktop
build with the new origin**. Otherwise the deployed server will reject desktop
requests until its allowlist is updated. The server retains the studio and
legacy Tauri origins so existing desktop releases continue working.
Check both repositories:
```sh
# From artcraft/
cargo test --offline -p artcraft_client_identity -p tauri-plugin-http --lib
# From artcraft-services/
cargo test --offline -p actix_cors_configs --lib
```
The server tests verify credentialed GET/POST requests and OPTIONS preflights in
production and development, rejection of lookalike domains/HTTP/alternate ports,
and compatibility with previous desktop origins. After server deployment, repeat
the native checks below using the updated app.
## Observed native results
These observations were captured with the earlier studio origin, before the
dedicated desktop origin migration. They do not establish that production has
deployed the new allowlist.
Checked in the real macOS Tauri dev app at `http://127.0.0.1:5193`, using its
existing session. Temporary probes were removed after verification. No cookies,
tokens, passwords, account identifiers, or media contents are recorded here.
| Check | Before | After |
|--------------------------------|---------------------------------------|----------------------------|
| Frontend HTTP `/v1/session` | 400, Origin rejected | 200 |
| Shared `UsersApi.GetSession()` | `success: false` | Success, logged in |
| Native vs. frontend identity | Frontend could not resolve an account | Same account |
| Shared media API, page size 1 | Not measured separately | Success, one item returned |
## Automated checks
From the repository root:
```sh
cargo test --offline -p tauri-plugin-http artcraft_origin --lib
./script/artcraft/unix_dev.sh
```
In a second terminal, substitute the URL printed by the launcher:
```sh
cd frontend
npm run test:desktop-session -- http://127.0.0.1:5193
```
The Rust tests cover the default port, alternate/collision ports, IPv4, IPv6,
localhost, packaged origins, duplicate headers, session-header preservation,
and destinations/origins that must remain unchanged.
The browser check uses the real frontend with an isolated Chrome profile and
mocked IPC. It verifies matching credits and Accounts state, a visible Library
image, media after opening the deferred image page, video/audio page rendering,
and logout followed by sign-in. It blocks remote browser traffic and never uses
your real account or native credentials. It requires installed Google Chrome.
It can also run against a locally served production frontend build.
These browser mocks cannot validate native transport or server CORS. The
performance fixture deliberately rejects HTTP requests and is **not** an
authentication acceptance test. Run the native check below when changing the
launcher, HTTP bridge, or authentication plumbing.
Validation on September 27: all 12 HTTP-plugin tests, 20 login-modal tests, and
10 app tests passed. The browser check passed against both the Vite dev server
and a fresh production build. To repeat the production check, serve a build in
one terminal, then pass its printed URL to `test:desktop-session` in another:
```sh
cd frontend/apps/artcraft
npm run build -- --outDir /tmp/artcraft-session-build
npm run preview -- --outDir /tmp/artcraft-session-build --host 127.0.0.1 --port 6215
```
## Repeat the real native check
1. Start the combined launcher, with an existing signed-in test session. Verify
Accounts displays that account, My Library loads its media, and Create Image,
Create Video, and Create Audio load their content.
2. Right-click inside the desktop webview, choose **Inspect Element**, and open
**Console**. Run this read-only probe. It prints statuses/counts, not credentials
or account/media contents:
```js
void (async () => {
const invoke = window.__TAURI_INTERNALS__.invoke;
const host = (await invoke("get_app_info_command")).payload.storyteller_host;
const options = { method: "GET", credentials: "include" };
const started = performance.now();
const [native, response] = await Promise.all([
invoke("storyteller_get_login_session_command"),
window.FetchProxy(`${host}/v1/session`, { ...options }),
]);
if (!response.ok) {
console.log({ origin: location.origin, sessionStatus: response.status });
return;
}
const session = await response.json();
const result = {
origin: location.origin,
sessionStatus: response.status,
nativeLoggedIn: !!native,
frontendLoggedIn: session.logged_in,
sameAccount: native?.user_token === session.user?.user_token,
sessionElapsedMs: performance.now() - started,
};
if (session.logged_in && session.user) {
const username = encodeURIComponent(session.user.username);
const media = await window.FetchProxy(
`${host}/v1/media_files/list/user/${username}?page_size=1`, { ...options },
);
result.mediaStatus = media.status;
if (media.ok) result.mediaCount = (await media.json()).results?.length;
}
console.log(result);
})().catch((error) => console.error("Desktop session probe failed", String(error)));
```
3. Repeat with a changed port (`ARTCRAFT_DEV_PORT=6200`) and with the starting
port occupied. For example, keep this listener running in another terminal
before starting the launcher; stop it with Ctrl-C afterward:
```sh
node -e 'require("node:net").createServer().listen(5193, "127.0.0.1")'
```
The launcher should select a later port, and both session transports should
still agree. An empty account may legitimately return zero media; it should
still return HTTP 200. Verify a genuinely signed-out session shows the login
screen using the isolated browser check, or a disposable account/profile.

224
docs/performance.md Normal file
View File

@ -0,0 +1,224 @@
# Desktop frontend performance experiments
Measured September 26, 2026 on an Apple M4 Pro, macOS arm64, Chrome
153.0.8010.53, Node 24.13.0. These are production frontend measurements in
headless Chrome with mocked Tauri services. They do **not** measure native
process launch, WKWebView/WebView2, Rust, disk startup, real account loading,
or generation latency.
These timings are not authentication acceptance tests: the benchmark mocks the
native session and rejects frontend HTTP requests. Before accepting a desktop
change, also run the [session and Library checks](desktop-session-regression.md),
including real Tauri HTTP requests when changing the launcher or bridge.
## Changes and results
Seven samples per version; table values are medians. Each sample uses a fresh
browser context at 1440 × 1000 with device scale 1 and browser HTTP cache
disabled. The browser process stays alive between samples. A reload in the
same context is measured separately. There is no CPU/network throttling.
External requests, including analytics, fonts, and media, are blocked in both
versions. The login fixture is signed in; the bundled model overlay is used.
| Measurement | Before | After | Reduction |
|-----------------------------|-----------|-----------|-----------|
| Startup to frame | 566.40 ms | 350.60 ms | 38.1% |
| Refresh to frame | 248.60 ms | 198.10 ms | 20.3% |
| Startup JavaScript | 9.05 MB | 6.47 MB | 28.6% |
| Startup long tasks (sum) | 336.00 ms | 184.00 ms | 45.2% |
| First drawing page to frame | 120.90 ms | 118.20 ms | 2.2% |
| Drawing to home: dispatch | 23.40 ms | 9.00 ms | 61.5% |
| Drawing to home: frame | 29.50 ms | 23.00 ms | 22.0% |
| Home to drawing: dispatch | 42.10 ms | 18.80 ms | 55.3% |
| Home to drawing: frame | 105.70 ms | 86.50 ms | 18.2% |
The 2.2% first-open difference is small enough to treat as unchanged. These
local measurements are evidence of reduced frontend work, not predictions
of identical percentage gains on every user's machine. Raw samples, ranges,
environment, fixture sizes, browser errors, and build provenance are in
[before.json](performance/2026-09-26-before.json) and
[after.json](performance/2026-09-26-after.json).
Three changes produced these results:
1. `MainApp.tsx` imported every editor at launch. Fifteen pages now use
`React.lazy` behind a Suspense boundary below the persistent shell. Their
code loads when selected; the top bar stays available during loading.
The default Apps page remains eager. Drawing also remains eager: its
shared code is already part of the shell, and experimentally deferring
its small host adapter made first-open latency worse for little saving.
First-open latency for the other deferred editors is a remaining tradeoff
to measure, especially on slower disks/CPUs. All 15 deferred modules were
imported successfully in the browser, but this is not an end-to-end test
of every editor's features.
2. `TabState.ts` exported the drawing scene to JSON when leaving and imported
it when returning. The Zustand scene store already survives page unmount.
With four imported images, the old path performed four FileReader reads
on exit and four more on return, allocated base64 copies, rebuilt image
nodes, cleared the selection, and appended an undo-history entry. Tab
changes now keep the live store. The measured round trip performs **zero
image-file reads**, preserves the selected node, and keeps history length
at one instead of growing to two. Explicit file export/import remains
available. Tests cover image identity, model metadata, selection, redo,
gallery reset, rapid navigation, and portable file export.
3. The shell ran `getGPUTier()` at startup and stored its result in an unread
React state value. Removing it eliminates **one startup WebGL context
request** and its associated detection work. The real 3D renderer still
creates its context when used. This experiment reports combined timing
gains, not an isolated timing attribution for each individual change.
## Repeat the experiment
From the repository root:
```sh
cd frontend
npm ci
npm run perf:desktop -- --output /tmp/artcraft-perf-current --smoke-imports
```
The default browser is an installed Google Chrome (`--channel chrome`). The
runner requires permission to launch a browser and bind a loopback server.
It never uses your regular browser profile, account, or native app data.
`@playwright/test` is pinned as a development dependency. Artifacts are written
outside the repository by default. Use a dedicated output directory: its
`dist` subdirectory is rebuilt by Vite.
For this particular two-module change, reproduce the original implementation
without replacing local source files:
```sh
npm run perf:desktop -- --output /tmp/artcraft-perf-before \
--baseline-ref 780e4494e995163fed1d677b88c3cf03b3fca63c
npm run perf:desktop -- --output /tmp/artcraft-perf-after --smoke-imports
node tools/performance/compare.mjs \
/tmp/artcraft-perf-before/results.json \
/tmp/artcraft-perf-after/results.json
```
`--baseline-ref` overlays **only** `MainApp.tsx` and `pages/Stores/TabState.ts`
from that Git revision in the benchmark build. All other source files and
dependencies remain current. It reproduces the two production files changed
in this experiment; it is not a general historical-checkout benchmark. For
future changes, capture a normal baseline **before** editing, use a new output
directory for the changed version, and keep the runner, fixture, dependencies,
browser, and machine identical. Run sequentially while the machine is idle;
do not build or run other CPU-heavy tasks during samples. Repeat in reverse
order if results are close or noisy.
Useful options:
```sh
# Build in a restricted shell, then run where browser/server use is allowed.
npm run perf:desktop -- --output /tmp/artcraft-perf-current --build-only
npm run perf:desktop -- --output /tmp/artcraft-perf-current --skip-build
# More samples; seven is the default.
npm run perf:desktop -- --output /tmp/artcraft-perf-current --runs 15
# Correctness checks for the navigation change.
npx vitest run --config apps/artcraft/vitest.config.ts
```
Do not use `--skip-build` after changing app code; it intentionally measures
the existing artifact. `build-info.json` records the revision, changed-file
names, baseline overlay, and build time. The benchmark plugin alone exposes
the stores needed to seed the scene. It is not part of the normal Vite/Tauri
build, and no mock IPC or benchmark global is added to the shipped app.
The runner builds from the app's working directory, matching its normal
build command. This matters because Tailwind resolves its config and content
relative to that directory. It rejects a run without working Tailwind styles
or with uncaught browser errors. `drawing.png` provides a visual check after
the measured operations. The initial unstyled exploratory runs were discarded.
## What the measurements mean
The fixture creates four deterministic 1024 × 1024 PNG image nodes and 80
strokes of 200 coordinates each, with one selected image. On the recorded
browser each PNG is 2,356,706 bytes. Fixture construction, image decoding,
and a one-second settling period are outside the tab-transition timings.
Each sample follows the same sequence:
1. Navigate to the production app, wait for the Apps heading and for the
signed-in login overlay to disappear, then wait two animation frames.
2. Reload that page and repeat the same readiness checks.
3. Seed the scene while on Apps, open drawing, and wait for its canvas and
two animation frames. Allow a second for its background bake to settle.
4. Switch to Apps and then back to drawing, measuring each separately.
5. After a settling period, inspect node count, selection, history, and IPC
counters. Save a screenshot on the first run. Optionally evaluate all
deferred page modules after the final timed operation.
`readyMs` is `performance.now()` after readiness checks and two animation
frames; its origin is navigation start. It includes browser loading and
automation readiness-observation overhead. `jsBytes` sums decoded resource
sizes of loaded JavaScript; it is uncompressed bytes, not all packaged files.
`longTaskMs` sums observed startup tasks longer than 50 ms, not total CPU time
or total blocking time. Long Tasks support is browser-dependent.
`stateReadyMs` measures the awaited `setActiveTab()` action, including React
work synchronously flushed by its store subscribers. `paintMs` continues
until the destination heading/canvas exists and two animation frames have
passed. This is a **rendering-opportunity proxy**, not proof of GPU presentation
or of every asynchronous image decode completing. In particular, the old
return path could still be decoding images after the canvas first appeared.
Tab measurements also create `artcraft:tab:APPS` and `artcraft:tab:2D` User
Timing entries in the benchmark page.
The runner calls the same store action used by navigation UI. It excludes
pointer-event dispatch, menu animations, and physical click-to-screen latency.
It does not automate paid generations, sign in to a real account, or measure
remote services. Save the raw JSON as well as the summary; a single minimum
time is not a reliable comparison.
`dist/performance-bundle.json` ranks the largest retained modules per chunk
and records chunk imports. Module `renderedBytes` is Rollup's intermediate
module size; it is useful for attribution but should not be summed as final
minified/gzipped size. Use actual resource bytes for the startup total.
## Remaining investigation
- The shell still loads about 6.47 MB of JavaScript. Shared imports through
drawing, scene, gallery, and settings entry points need a deeper dependency
audit. Separate lightweight store/type imports from editor code, then use
the bundle report and the same startup experiment to verify what actually
leaves the initial graph. The report identifies Spark, Three.js core and
renderer, the inline FBX-to-GLB conversion worker, PostHog, and Mediabunny
among the largest retained modules. Their presence is measured; the runtime
benefit of deferring each individually has not yet been measured.
- Returning to the populated canvas still takes about 86 ms. The editor
remount, Konva drawing, image/transformer setup, and composite bake need a
timeline profile before choosing the next change. Keep scene restoration,
undo, selection, and background generation behavior in correctness checks.
- `TaskQueue.tsx` polls every five seconds and rebuilds task arrays even when
the popover is closed. The benchmark uses an empty queue, so it does not
establish the cost for a large real queue. A fixed, representative task
fixture plus idle CPU/render counts is the next useful experiment there.
- `useStageSnapshot` looks expensive in isolation, but its only call is
commented out in `PaintSurface.tsx`. It was excluded as a current bottleneck.
Validation completed: normal production Vite build, all 10 app tests and 20
login tests, all 15 deferred page-module imports, visual canvas inspection,
and a check that the normal build contains no benchmark globals or fixtures.
The broad TypeScript check remains blocked by existing workspace declaration/
project-reference errors and Remix/Deno types. Comparing diagnostics with the
two original modules showed the same diagnostic messages (some import traces
and reporting locations changed); this is not a clean typecheck claim.
## Validate in the native app
Before claiming native launch or interaction gains, run matching release
Tauri builds on the same machine and WebView version. Keep account, window
size, network conditions, and canvas artwork fixed. Record the Web Inspector
timeline for launch/reload, opening a tool for the first time, drawing → Apps,
and Apps → drawing. Repeat at least seven times and retain the traces with
build IDs and medians. Separate native process launch from page reload; do
not mix dev/HMR traces with production measurements.
For canvas tests, create a blank 1024-square canvas, import the same four
images, add the same strokes, select an image, and wait for background work
before switching. Check image content, selection, undo/redo, and opening a new
gallery image afterward. Record actual click-to-visible-frame latency in
the inspector as well as JavaScript tasks. The browser results above justify
the code changes but do not replace that native validation.

View File

@ -0,0 +1,527 @@
{
"timestamp": "2026-09-27T00:32:54.524Z",
"build": {
"builtAt": "2026-09-27T00:30:35.760Z",
"revision": "780e4494e995163fed1d677b88c3cf03b3fca63c",
"baselineOverlay": null,
"changedFiles": [
"frontend/apps/artcraft/app/src/pages/MainApp.tsx",
"frontend/apps/artcraft/app/src/pages/Stores/TabState.ts",
"frontend/package-lock.json",
"frontend/package.json"
]
},
"environment": {
"platform": "darwin",
"arch": "arm64",
"cpu": "Apple M4 Pro",
"browser": "153.0.8010.53",
"node": "v24.13.0",
"runs": 7,
"viewport": "1440x1000@1",
"ipc": "mocked",
"network": "local assets only, browser cache disabled"
},
"summary": {
"startup": {
"readyMs": {
"median": 350.60000002384186,
"min": 348.7000000476837,
"max": 457.39999997615814
},
"jsBytes": {
"median": 6466606,
"min": 6466606,
"max": 6466606
},
"longTaskMs": {
"median": 184,
"min": 179,
"max": 284
},
"webglContexts": {
"median": 0,
"min": 0,
"max": 0
}
},
"refresh": {
"readyMs": {
"median": 198.10000002384186,
"min": 197.10000002384186,
"max": 198.80000007152557
},
"jsBytes": {
"median": 6466606,
"min": 6466606,
"max": 6466606
},
"longTaskMs": {
"median": 0,
"min": 0,
"max": 0
},
"webglContexts": {
"median": 0,
"min": 0,
"max": 0
}
},
"firstDraw": {
"stateReadyMs": {
"median": 38.300000071525574,
"min": 37.60000002384186,
"max": 40.299999952316284
},
"paintMs": {
"median": 118.19999992847443,
"min": 115.30000007152557,
"max": 120
},
"fileReads": {
"median": 0,
"min": 0,
"max": 0
}
},
"leaveDraw": {
"stateReadyMs": {
"median": 9,
"min": 7.5,
"max": 11
},
"paintMs": {
"median": 23,
"min": 19.600000023841858,
"max": 26.600000023841858
},
"fileReads": {
"median": 0,
"min": 0,
"max": 0
}
},
"returnDraw": {
"stateReadyMs": {
"median": 18.800000071525574,
"min": 15.799999952316284,
"max": 20.700000047683716
},
"paintMs": {
"median": 86.5,
"min": 78.79999995231628,
"max": 90.10000002384186
},
"fileReads": {
"median": 0,
"min": 0,
"max": 0
}
}
},
"samples": [
{
"startup": {
"readyMs": 457.39999997615814,
"jsBytes": 6466606,
"longTaskMs": 284,
"webglContexts": 0
},
"refresh": {
"readyMs": 197.80000007152557,
"jsBytes": 6466606,
"longTaskMs": 0,
"webglContexts": 0
},
"firstDraw": {
"stateReadyMs": 38.800000071525574,
"paintMs": 119.5,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 7.600000023841858,
"paintMs": 20.399999976158142,
"fileReads": 0
},
"returnDraw": {
"stateReadyMs": 17.799999952316284,
"paintMs": 87.79999995231628,
"fileReads": 0
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 1,
"historyLength": 1,
"commands": {
"plugin:event|listen": 25,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 365.7999999523163,
"jsBytes": 6466606,
"longTaskMs": 185,
"webglContexts": 0
},
"refresh": {
"readyMs": 197.10000002384186,
"jsBytes": 6466606,
"longTaskMs": 0,
"webglContexts": 0
},
"firstDraw": {
"stateReadyMs": 37.60000002384186,
"paintMs": 116,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 7.5,
"paintMs": 26.600000023841858,
"fileReads": 0
},
"returnDraw": {
"stateReadyMs": 15.799999952316284,
"paintMs": 78.79999995231628,
"fileReads": 0
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 1,
"historyLength": 1,
"commands": {
"plugin:event|listen": 25,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 366.59999990463257,
"jsBytes": 6466606,
"longTaskMs": 193,
"webglContexts": 0
},
"refresh": {
"readyMs": 198.39999997615814,
"jsBytes": 6466606,
"longTaskMs": 0,
"webglContexts": 0
},
"firstDraw": {
"stateReadyMs": 40.299999952316284,
"paintMs": 118.19999992847443,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 9,
"paintMs": 23,
"fileReads": 0
},
"returnDraw": {
"stateReadyMs": 19.699999928474426,
"paintMs": 86.5,
"fileReads": 0
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 1,
"historyLength": 1,
"commands": {
"plugin:event|listen": 25,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 348.7000000476837,
"jsBytes": 6466606,
"longTaskMs": 184,
"webglContexts": 0
},
"refresh": {
"readyMs": 197.89999997615814,
"jsBytes": 6466606,
"longTaskMs": 0,
"webglContexts": 0
},
"firstDraw": {
"stateReadyMs": 37.700000047683716,
"paintMs": 115.60000002384186,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 9.300000071525574,
"paintMs": 26.40000009536743,
"fileReads": 0
},
"returnDraw": {
"stateReadyMs": 18.700000047683716,
"paintMs": 84.90000009536743,
"fileReads": 0
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 1,
"historyLength": 1,
"commands": {
"plugin:event|listen": 25,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 349.60000002384186,
"jsBytes": 6466606,
"longTaskMs": 179,
"webglContexts": 0
},
"refresh": {
"readyMs": 198.10000002384186,
"jsBytes": 6466606,
"longTaskMs": 0,
"webglContexts": 0
},
"firstDraw": {
"stateReadyMs": 38.300000071525574,
"paintMs": 118.5,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 11,
"paintMs": 19.600000023841858,
"fileReads": 0
},
"returnDraw": {
"stateReadyMs": 20.700000047683716,
"paintMs": 90.10000002384186,
"fileReads": 0
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 1,
"historyLength": 1,
"commands": {
"plugin:event|listen": 25,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 350.60000002384186,
"jsBytes": 6466606,
"longTaskMs": 179,
"webglContexts": 0
},
"refresh": {
"readyMs": 198.20000004768372,
"jsBytes": 6466606,
"longTaskMs": 0,
"webglContexts": 0
},
"firstDraw": {
"stateReadyMs": 39.60000002384186,
"paintMs": 120,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 11,
"paintMs": 22.199999928474426,
"fileReads": 0
},
"returnDraw": {
"stateReadyMs": 20,
"paintMs": 87,
"fileReads": 0
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 1,
"historyLength": 1,
"commands": {
"plugin:event|listen": 25,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 349.89999997615814,
"jsBytes": 6466606,
"longTaskMs": 180,
"webglContexts": 0
},
"refresh": {
"readyMs": 198.80000007152557,
"jsBytes": 6466606,
"longTaskMs": 0,
"webglContexts": 0
},
"firstDraw": {
"stateReadyMs": 38,
"paintMs": 115.30000007152557,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 8.200000047683716,
"paintMs": 24.899999976158142,
"fileReads": 0
},
"returnDraw": {
"stateReadyMs": 18.800000071525574,
"paintMs": 84.5,
"fileReads": 0
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 1,
"historyLength": 1,
"commands": {
"plugin:event|listen": 25,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
}
],
"importedPages": [
"src/pages/PageAngles/index.ts",
"src/pages/PageAudio/CreateAudio.tsx",
"src/pages/PageBackgroundChange/index.ts",
"src/pages/PageImage/TextToImage.tsx",
"src/pages/PageImageTo3DObject/index.ts",
"src/pages/PageImageTo3DWorld/index.ts",
"src/pages/PageImageWatermarkRemover/index.ts",
"src/pages/PageMoodboard/index.ts",
"src/pages/PageRemoveBackground/index.ts",
"src/pages/PageScene/index.tsx",
"src/pages/PageStoryboard/index.ts",
"src/pages/PageVideo/ImageToVideo.tsx",
"src/pages/PageVideoEditor/index.tsx",
"src/pages/PageVideoFrameExtractor/index.ts",
"src/pages/PageVideoWatermarkRemover/index.ts"
],
"errors": []
}

View File

@ -0,0 +1,510 @@
{
"timestamp": "2026-09-27T00:30:21.217Z",
"build": {
"builtAt": "2026-09-27T00:28:39.209Z",
"revision": "780e4494e995163fed1d677b88c3cf03b3fca63c",
"baselineOverlay": "HEAD",
"changedFiles": [
"frontend/apps/artcraft/app/src/pages/MainApp.tsx",
"frontend/apps/artcraft/app/src/pages/Stores/TabState.ts",
"frontend/package-lock.json",
"frontend/package.json"
]
},
"environment": {
"platform": "darwin",
"arch": "arm64",
"cpu": "Apple M4 Pro",
"browser": "153.0.8010.53",
"node": "v24.13.0",
"runs": 7,
"viewport": "1440x1000@1",
"ipc": "mocked",
"network": "local assets only, browser cache disabled"
},
"summary": {
"startup": {
"readyMs": {
"median": 566.3999999761581,
"min": 532.3999999761581,
"max": 847.7999999523163
},
"jsBytes": {
"median": 9052991,
"min": 9052991,
"max": 9052991
},
"longTaskMs": {
"median": 336,
"min": 314,
"max": 407
},
"webglContexts": {
"median": 1,
"min": 1,
"max": 1
}
},
"refresh": {
"readyMs": {
"median": 248.60000002384186,
"min": 247.59999990463257,
"max": 351.1999999284744
},
"jsBytes": {
"median": 9052991,
"min": 9052991,
"max": 9052991
},
"longTaskMs": {
"median": 0,
"min": 0,
"max": 0
},
"webglContexts": {
"median": 1,
"min": 1,
"max": 1
}
},
"firstDraw": {
"stateReadyMs": {
"median": 40.40000009536743,
"min": 37.299999952316284,
"max": 43.299999952316284
},
"paintMs": {
"median": 120.90000009536743,
"min": 117.89999997615814,
"max": 126.79999995231628
},
"fileReads": {
"median": 0,
"min": 0,
"max": 0
}
},
"leaveDraw": {
"stateReadyMs": {
"median": 23.399999976158142,
"min": 20.100000023841858,
"max": 26
},
"paintMs": {
"median": 29.5,
"min": 21.200000047683716,
"max": 35.5
},
"fileReads": {
"median": 4,
"min": 4,
"max": 4
}
},
"returnDraw": {
"stateReadyMs": {
"median": 42.10000002384186,
"min": 36.59999990463257,
"max": 45.200000047683716
},
"paintMs": {
"median": 105.69999992847443,
"min": 100.89999997615814,
"max": 109.20000004768372
},
"fileReads": {
"median": 4,
"min": 4,
"max": 4
}
}
},
"samples": [
{
"startup": {
"readyMs": 847.7999999523163,
"jsBytes": 9052991,
"longTaskMs": 407,
"webglContexts": 1
},
"refresh": {
"readyMs": 351.1999999284744,
"jsBytes": 9052991,
"longTaskMs": 0,
"webglContexts": 1
},
"firstDraw": {
"stateReadyMs": 43.299999952316284,
"paintMs": 126.79999995231628,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 25.100000023841858,
"paintMs": 35.5,
"fileReads": 4
},
"returnDraw": {
"stateReadyMs": 36.59999990463257,
"paintMs": 100.89999997615814,
"fileReads": 4
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 0,
"historyLength": 2,
"commands": {
"plugin:event|listen": 26,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 539.3999999761581,
"jsBytes": 9052991,
"longTaskMs": 317,
"webglContexts": 1
},
"refresh": {
"readyMs": 264.60000002384186,
"jsBytes": 9052991,
"longTaskMs": 0,
"webglContexts": 1
},
"firstDraw": {
"stateReadyMs": 39.39999997615814,
"paintMs": 120.20000004768372,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 20.100000023841858,
"paintMs": 21.200000047683716,
"fileReads": 4
},
"returnDraw": {
"stateReadyMs": 41.60000002384186,
"paintMs": 104.60000002384186,
"fileReads": 4
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 0,
"historyLength": 2,
"commands": {
"plugin:event|listen": 26,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 561.9000000953674,
"jsBytes": 9052991,
"longTaskMs": 329,
"webglContexts": 1
},
"refresh": {
"readyMs": 248.19999992847443,
"jsBytes": 9052991,
"longTaskMs": 0,
"webglContexts": 1
},
"firstDraw": {
"stateReadyMs": 40.40000009536743,
"paintMs": 120.90000009536743,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 23.399999976158142,
"paintMs": 33.39999997615814,
"fileReads": 4
},
"returnDraw": {
"stateReadyMs": 37.299999952316284,
"paintMs": 101.10000002384186,
"fileReads": 4
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 0,
"historyLength": 2,
"commands": {
"plugin:event|listen": 26,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 569.5,
"jsBytes": 9052991,
"longTaskMs": 336,
"webglContexts": 1
},
"refresh": {
"readyMs": 248,
"jsBytes": 9052991,
"longTaskMs": 0,
"webglContexts": 1
},
"firstDraw": {
"stateReadyMs": 38,
"paintMs": 119.30000007152557,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 26,
"paintMs": 34.799999952316284,
"fileReads": 4
},
"returnDraw": {
"stateReadyMs": 45.200000047683716,
"paintMs": 109.20000004768372,
"fileReads": 4
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 0,
"historyLength": 2,
"commands": {
"plugin:event|listen": 26,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 567.5,
"jsBytes": 9052991,
"longTaskMs": 339,
"webglContexts": 1
},
"refresh": {
"readyMs": 248.60000002384186,
"jsBytes": 9052991,
"longTaskMs": 0,
"webglContexts": 1
},
"firstDraw": {
"stateReadyMs": 40.89999997615814,
"paintMs": 122.10000002384186,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 23.200000047683716,
"paintMs": 29.5,
"fileReads": 4
},
"returnDraw": {
"stateReadyMs": 42.10000002384186,
"paintMs": 105.69999992847443,
"fileReads": 4
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 0,
"historyLength": 2,
"commands": {
"plugin:event|listen": 26,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 566.3999999761581,
"jsBytes": 9052991,
"longTaskMs": 336,
"webglContexts": 1
},
"refresh": {
"readyMs": 281.39999997615814,
"jsBytes": 9052991,
"longTaskMs": 0,
"webglContexts": 1
},
"firstDraw": {
"stateReadyMs": 43.09999990463257,
"paintMs": 124.69999992847443,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 23.399999976158142,
"paintMs": 26.199999928474426,
"fileReads": 4
},
"returnDraw": {
"stateReadyMs": 42.799999952316284,
"paintMs": 107.19999992847443,
"fileReads": 4
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 0,
"historyLength": 2,
"commands": {
"plugin:event|listen": 26,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
},
{
"startup": {
"readyMs": 532.3999999761581,
"jsBytes": 9052991,
"longTaskMs": 314,
"webglContexts": 1
},
"refresh": {
"readyMs": 247.59999990463257,
"jsBytes": 9052991,
"longTaskMs": 0,
"webglContexts": 1
},
"firstDraw": {
"stateReadyMs": 37.299999952316284,
"paintMs": 117.89999997615814,
"fileReads": 0
},
"leaveDraw": {
"stateReadyMs": 21.5,
"paintMs": 22.899999976158142,
"fileReads": 4
},
"returnDraw": {
"stateReadyMs": 44.09999990463257,
"paintMs": 108.39999997615814,
"fileReads": 4
},
"fixture": {
"images": 4,
"imageSize": 1024,
"imageBytesEach": 2356706,
"strokes": 80,
"coordinatesPerStroke": 200
},
"afterReturn": {
"nodeCount": 84,
"selectedCount": 0,
"historyLength": 2,
"commands": {
"plugin:event|listen": 26,
"get_app_info_command": 1,
"list_image_models_command": 1,
"list_video_models_command": 1,
"get_task_queue_command": 1,
"estimate_image_cost_command": 5,
"storyteller_get_login_session_command": 1,
"plugin:http|fetch": 5,
"storyteller_get_credits_command": 1,
"storyteller_get_subscription_command": 1,
"plugin:window|is_maximized": 1,
"plugin:event|unlisten": 2
}
}
}
],
"errors": []
}

80
docs/website-login.md Normal file
View File

@ -0,0 +1,80 @@
# Website login from the desktop app
The React login/signup dialog calls Tauri commands only, including its startup
session check and password forms. Website and QR actions appear only in login
mode. Tauri never connects to MySQL; the desktop uses Rust HTTP API bindings. Creating/polling login challenges and
verifying `/v1/session` use `artcraft_client::endpoints::users::login_challenges`.
The Rust command uses `AppEnvConfigs.storyteller_host` for every request, keeps the
private device token in native memory, and returns only a local challenge handle,
approval URL/code/deadline, status, and the verified user to JavaScript. The signed
session cookie never crosses IPC or gets written to JavaScript local storage.
After redemption, Rust verifies the signed session against the same API host,
installs the server's cookie into the native HTTP jar and credential manager, and
persists the jar. Closing the dialog removes the local handle; a cancellation
while HTTP is in flight prevents installing the late response. Retries retrieve
the same server session. Neither creation nor website approval pre-creates one.
## Session response compatibility
A server feature flag added after a desktop release must not prevent login. The
session decoder keeps known feature flags and ignores unknown flag names, such
as `use_qt` on older clients. Malformed flag values and required authentication
fields still fail validation. Tests cover a real Rust HTTP session response with
both known and future flags, followed by native cookie installation/persistence.
A late startup session check cannot reset an active or completed website login.
## Diagnosing 401 responses
`storyteller_activity_thread` reports errors from `/v1/analytics/active_user_v2`.
This is the background activity ping, not the login-challenge endpoint. It requires
a user session. An anonymous `visitor` cookie alone is now skipped. Expired or
revoked sessions can still produce a 401 and require signing in again.
Activity failures log the configured API origin (including port), endpoint, and
error. Native website-login requests/failures log origin, endpoint, and HTTP
status. Request bodies, device tokens, approval URLs, and signed cookies are not
logged by the new client, including at debug level.
## API environment
`~/Artcraft/settings/env_configs.json` controls the native API host:
```json
{"storyteller_host":"localhost","storyteller_port":12345}
```
Local mode uses `http://localhost:12345` and a local approval website at
`http://localhost:4201/login/desktop`. Run storyteller-web with its migrations
applied, and the services webapp with `USE_LOCAL_API=1`. The local website must
also use the local API. A challenge in a local database cannot be approved on the
production website, even when that browser already has a production session.
For the production API and production website, use `"storyteller_host":"production"`
(or omit the override), then restart ArtCraft. API host configuration is not
silently changed by login. Local and production approval URLs cannot be mixed.
Localhost development URLs are for the same computer; mobile QR testing needs
a shared/deployed environment.
## Tests
From the desktop repository:
```sh
SQLX_OFFLINE=true cargo test --offline -p artcraft --lib login_bridge_tests
cd frontend
npm exec vitest -- run --config libs/components/login-modal/vite.config.ts src/lib/DesktopLoginBridge.spec.tsx src/lib/login-modal.spec.tsx
```
Native tests use only ephemeral loopback HTTP servers and temporary cookie stores.
They exercise the real API bindings and the command implementation, including
cookie verification/persistence, rejection, expiry, retries, in-flight cancellation,
origin separation, no redirects, redacted errors, visitor-only telemetry, future
feature flags, malformed session data, and password login/signup/session checks.
UI tests prohibit JavaScript HTTP and runtime API imports. They verify the IPC
contract, native browser opening, QR/code display, status, backoff, cleanup,
login-only button placement, native password forms, and stale session responses.
The services repository also has real MySQL integration tests for approval,
redemption, rejection, concurrency, and downstream authentication, using isolated
local databases. No test contacts a production API or database.

View File

@ -31,7 +31,7 @@
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght@100..900&family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap"
<link href="https://fonts.googleapis.com/css2?family=Archivo:wdth,wght@62..125,100..900&family=Instrument+Serif:ital@0;1&family=Geist+Mono:wght@300..800&display=swap"
rel="stylesheet" />
<!-- <link rel="stylesheet" href="/src/styles.css" /> -->
</head>

View File

@ -191,11 +191,11 @@ export function GlobalFileDropHandler() {
return (
<>
{isDragging && modalType === null && (
<div className="pointer-events-none fixed inset-0 z-[9999] flex items-center justify-center bg-black/40">
<div className="flex flex-col items-center gap-3 rounded-2xl border-2 border-dashed border-white/60 bg-black/30 px-16 py-12 text-white backdrop-blur-sm">
<Maximize2Icon className="text-4xl opacity-80" />
<div className="text-xl font-semibold">Drop to Upload</div>
<div className="text-sm opacity-60">GLB, PNG, JPG, JPEG, SPZ</div>
<div className="pointer-events-none fixed inset-0 z-[9999] flex items-center justify-center bg-black/70">
<div className="flex flex-col items-center gap-3 border border-dashed border-white/60 bg-ui-panel px-16 py-12 text-white">
<Maximize2Icon className="text-3xl opacity-60" />
<div className="font-display text-2xl tracking-tight">Drop to Upload</div>
<div className="hud-label text-white/50">GLB, PNG, JPG, JPEG, SPZ</div>
</div>
</div>
)}

View File

@ -36,6 +36,7 @@ import {
useCostBreakdownModalStore,
} from "@storyteller/ui-pricing-modal";
import { HelpMenuButton } from "@storyteller/ui-help-menu";
import { CreateEmptyState } from "~/components/generation-feed/CreateEmptyState";
type Mode = "image" | "text";
type Variant = "object" | "world";
@ -549,9 +550,9 @@ export const ImageTo3DExperience = ({
role="button"
tabIndex={0}
className={twMerge(
"flex flex-col items-center justify-center rounded-2xl border-[3px] border-dashed border-primary/40 bg-primary/5 text-center text-xs transition-all hover:border-primary hover:bg-primary/10 focus:outline-none focus:ring-2 focus:ring-primary/40",
"flex flex-col items-center justify-center border border-dashed border-white/20 bg-white/[0.015] text-center text-xs transition-all hover:border-white/40 hover:bg-white/5 focus:border-white/60 focus:outline-none",
hasResults ? "aspect-square w-24" : "aspect-square w-48",
dragActive && "border-primary bg-primary/10",
dragActive && "border-white/60 bg-white/5",
)}
onDragEnter={(event) => {
event.preventDefault();
@ -581,11 +582,11 @@ export const ImageTo3DExperience = ({
<PlusIcon
className={twMerge(
"text-base-fg opacity-90 drop-shadow",
"text-base-fg opacity-80",
hasResults ? "text-2xl" : "text-4xl",
)} />
{!hasResults && (
<span className="mt-3 text-[15px] font-medium text-base-fg opacity-60">
<span className="mt-3 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
Add Image
</span>
)}
@ -598,7 +599,7 @@ export const ImageTo3DExperience = ({
{uploadedPreview ? (
<div
className={twMerge(
"group relative cursor-pointer overflow-hidden rounded-2xl border-[3px] border-primary/40 bg-black/30 transition-all",
"group relative cursor-pointer overflow-hidden border border-white/30 bg-black/30 transition-all hover:border-white/60",
hasResults ? "aspect-square w-24" : "aspect-square w-48",
)}
onClick={() => !isUploading && fileInputRef.current?.click()}
@ -613,13 +614,13 @@ export const ImageTo3DExperience = ({
/>
{isUploading && (
<div className="absolute inset-0 flex items-center justify-center">
<div className="h-8 w-8 animate-spin rounded-full border-[3px] border-white/30 border-t-primary" />
<div className="h-8 w-8 animate-spin rounded-full border-[3px] border-white/30 border-t-white" />
</div>
)}
{!isUploading && (
<button
type="button"
className="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-full bg-black/60 text-white opacity-0 transition-opacity group-hover:opacity-100"
className="absolute right-2 top-2 flex h-6 w-6 items-center justify-center rounded-[3px] bg-black/60 text-white opacity-0 transition-all hover:bg-black group-hover:opacity-100"
onClick={(event) => {
event.stopPropagation();
setUploadedPreview(null);
@ -645,7 +646,7 @@ export const ImageTo3DExperience = ({
ref={textareaRef}
id={promptInputId}
rows={1}
className="text-md max-h-[5.5em] w-full resize-none overflow-y-auto rounded bg-transparent pr-2 pt-1 text-base-fg placeholder-base-fg/60 focus:outline-none"
className="text-md max-h-[5.5em] w-full resize-none overflow-y-auto rounded-[3px] bg-transparent pr-2 pt-1 text-base-fg placeholder-base-fg/60 focus:outline-none"
value={prompt}
placeholder="Describe any object you want to generate from scratch..."
onChange={(event) => setPrompt(event.target.value)}
@ -691,8 +692,8 @@ export const ImageTo3DExperience = ({
role="button"
tabIndex={0}
className={twMerge(
"flex h-32 w-32 flex-col items-center justify-center rounded-xl border-2 border-dashed border-primary/40 bg-primary/5 transition-all hover:border-primary hover:bg-primary/10 focus:outline-none focus:ring-2 focus:ring-primary/40",
dragActive && "border-primary bg-primary/10",
"flex h-32 w-32 flex-col items-center justify-center border border-dashed border-white/20 bg-white/[0.015] transition-all hover:border-white/40 hover:bg-white/5 focus:border-white/60 focus:outline-none",
dragActive && "border-white/60 bg-white/5",
)}
onDragEnter={(e) => {
e.preventDefault();
@ -730,8 +731,8 @@ export const ImageTo3DExperience = ({
>
<PlusIcon
className="text-3xl text-base-fg opacity-90 drop-shadow" />
<span className="mt-2 text-sm font-medium text-base-fg/50">
className="text-3xl text-base-fg opacity-80" />
<span className="mt-2 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
Add Images
</span>
</div>
@ -740,7 +741,7 @@ export const ImageTo3DExperience = ({
<textarea
ref={worldTextareaRef}
rows={2}
className="w-full resize-none overflow-y-auto rounded-lg bg-white/5 px-3 py-2.5 text-base text-base-fg placeholder-base-fg/60 outline-none ring-2 ring-transparent transition-all focus:ring-primary/80"
className="w-full resize-none overflow-y-auto rounded-[3px] border border-white/15 bg-ui-controls px-3 py-2.5 text-base text-base-fg placeholder-base-fg/60 transition-colors focus:border-white/60 focus:outline-none"
style={{ maxHeight: "5em" }}
value={worldPrompt}
placeholder="Describe your 3D world (optional)..."
@ -754,7 +755,7 @@ export const ImageTo3DExperience = ({
<div
key={img.id}
className={twMerge(
"glass group relative aspect-square overflow-hidden rounded-lg border-2 border-white/30 transition-all",
"group relative aspect-square overflow-hidden rounded-[3px] border border-white/30 bg-black/30 transition-all",
hasResults ? "w-10" : "w-auto",
img.isUploading
? "cursor-default"
@ -772,13 +773,13 @@ export const ImageTo3DExperience = ({
/>
{img.isUploading && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20">
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-primary" />
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
</div>
)}
{!img.isUploading && (
<button
type="button"
className="absolute right-[2px] top-[2px] flex h-4 w-4 cursor-pointer items-center justify-center rounded-full bg-black/50 text-white opacity-0 backdrop-blur-md transition-colors hover:bg-red/70 group-hover:opacity-100"
className="absolute right-[2px] top-[2px] flex h-4 w-4 cursor-pointer items-center justify-center rounded-[3px] bg-black/60 text-white opacity-0 transition-colors hover:bg-red/70 group-hover:opacity-100"
onClick={(e) => {
e.stopPropagation();
removeWorldImage(img.id);
@ -820,7 +821,7 @@ export const ImageTo3DExperience = ({
<Button
variant="action"
className={twMerge(
"aspect-square overflow-hidden rounded-lg border-2 border-dashed border-black/5 bg-ui-controls/40 transition-all hover:bg-ui-controls/60 dark:border-white/25",
"aspect-square overflow-hidden rounded-[3px] border border-dashed border-black/15 bg-white/5 transition-all hover:border-white/40 hover:bg-white/10 dark:border-white/25",
hasResults ? "w-10" : "w-14",
)}
onClick={() => worldFileInputRef.current?.click()}
@ -836,7 +837,7 @@ export const ImageTo3DExperience = ({
);
const imageCountRow = (
<div className="flex items-center justify-center gap-2 text-xs text-base-fg/40">
<div className="flex items-center justify-center gap-2 font-mono text-[11px] tabular-nums text-base-fg/40">
<span>
{worldImages.length}/{MAX_WORLD_IMAGES} images
</span>
@ -865,7 +866,7 @@ export const ImageTo3DExperience = ({
<textarea
ref={worldTextareaRef}
rows={1}
className="flex-1 resize-none overflow-y-auto rounded-lg bg-white/5 px-3 py-2 text-sm text-base-fg placeholder-base-fg/60 focus:outline-none focus:ring-2 focus:ring-primary/60"
className="flex-1 resize-none overflow-y-auto rounded-[3px] border border-white/15 bg-ui-controls px-3 py-2 text-sm text-base-fg placeholder-base-fg/60 transition-colors focus:border-white/60 focus:outline-none"
value={worldPrompt}
placeholder="Describe world (optional)..."
onChange={(e) => setWorldPrompt(e.target.value)}
@ -887,7 +888,7 @@ export const ImageTo3DExperience = ({
<textarea
ref={worldTextareaRef}
rows={2}
className="w-full resize-none overflow-y-auto rounded-lg bg-white/5 px-3 py-2.5 text-base text-base-fg placeholder-base-fg/60 focus:outline-none focus:ring-2 focus:ring-primary/60"
className="w-full resize-none overflow-y-auto rounded-[3px] border border-white/15 bg-ui-controls px-3 py-2.5 text-base text-base-fg placeholder-base-fg/60 transition-colors focus:border-white/60 focus:outline-none"
style={{ maxHeight: "5em" }}
value={worldPrompt}
placeholder="Describe your 3D world (optional)..."
@ -907,7 +908,7 @@ export const ImageTo3DExperience = ({
results.find((r) => r.id === selectedResultId) || results[0];
return (
<div className="bg-ui-panel-gradient flex h-[calc(100vh-56px)] w-full bg-ui-panel text-base-fg">
<div className="flex h-[calc(100vh-56px)] w-full bg-ui-background text-base-fg">
{backgroundImage && !hasResults && (
<>
<div className="pointer-events-none fixed inset-0 z-[1] overflow-hidden bg-[radial-gradient(50%_50%_at_50%_50%,_transparent_49%,_rgb(var(--st-controls-rgb)_/_var(--st-gallery-vignette-alpha))_100%)]" />
@ -928,9 +929,12 @@ export const ImageTo3DExperience = ({
<div className="relative z-10 h-full w-full p-8">
{!hasResults && (
<div className="pointer-events-none absolute left-0 top-[calc(50%-280px)] w-full text-center">
<h1 className="mb-3 text-7xl font-bold tracking-tight">{title}</h1>
<p className="text-xl text-base-fg/70">{subtitle}</p>
<div className="pointer-events-none absolute left-0 top-[calc(50%-280px)] flex w-full justify-center">
<CreateEmptyState
title={title}
subtitle={subtitle}
className="py-8 sm:py-8"
/>
</div>
)}
@ -944,7 +948,7 @@ export const ImageTo3DExperience = ({
style={{ height: `calc(100vh - ${bottomOffsetPx + 80}px)` }}
>
{/* Left: Viewer */}
<div className="glass relative h-full overflow-hidden rounded-xl border border-ui-panel-border">
<div className="relative h-full overflow-hidden border border-ui-panel-border bg-ui-panel">
<Viewer3D
key={activeResult?.id}
modelUrl={activeResult?.modelUrl}
@ -1002,13 +1006,15 @@ export const ImageTo3DExperience = ({
</div>
{/* Right: History List */}
<div className="glass flex h-full flex-col overflow-hidden rounded-xl border border-ui-panel-border">
<div className="flex items-center justify-between p-4">
<h3 className="font-semibold text-base-fg/80">History</h3>
<div className="flex h-full flex-col overflow-hidden border border-ui-panel-border bg-ui-panel">
<div className="flex items-center justify-between border-b border-ui-panel-border px-4 py-3">
<h3 className="font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
History
</h3>
{results.length > 0 && (
<button
onClick={resetResults}
className="rounded-md bg-red/20 px-3 py-1 text-xs text-white/70 transition-colors hover:bg-red/30"
className="rounded-[3px] border border-red/40 bg-red/10 px-3 py-1 text-xs text-white/70 transition-colors hover:bg-red/20"
>
Clear Session
</button>
@ -1024,13 +1030,13 @@ export const ImageTo3DExperience = ({
key={result.id}
onClick={() => setSelectedResultId(result.id)}
className={twMerge(
"group flex w-full items-center gap-3 rounded-xl border p-2 text-left transition-all hover:bg-ui-controls/40",
"group flex w-full items-center gap-3 rounded-none border p-2 text-left transition-all hover:bg-white/5",
isSelected
? "border-primary/50 bg-primary/10"
: "border-transparent bg-ui-controls/20",
? "border-white bg-white/10"
: "border-white/10 bg-transparent hover:border-white/30",
)}
>
<div className="relative aspect-square h-14 w-14 shrink-0 overflow-hidden rounded-lg bg-black/30 ring-1 ring-white/5">
<div className="relative aspect-square h-14 w-14 shrink-0 overflow-hidden border border-white/10 bg-black/30">
{result.previewUrl ? (
<img
src={result.previewUrl}
@ -1049,7 +1055,7 @@ export const ImageTo3DExperience = ({
)}
{isPending && (
<div className="absolute inset-0 flex items-center justify-center bg-black/30">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white/20 border-t-primary" />
<div className="h-5 w-5 animate-spin rounded-full border-2 border-white/20 border-t-white" />
</div>
)}
</div>
@ -1063,7 +1069,7 @@ export const ImageTo3DExperience = ({
Generating…
</span>
) : (
<span className="text-base-fg/45">
<span className="font-mono tabular-nums text-base-fg/45">
{formatTime(result.timestamp)}
</span>
)}
@ -1093,7 +1099,7 @@ export const ImageTo3DExperience = ({
<div ref={promptContentRef}>
<div
className={twMerge(
"glass w-full rounded-xl shadow-2xl ring-1 ring-white/10",
"glass w-full",
hasResults ? "p-3" : "p-5",
)}
>
@ -1138,7 +1144,7 @@ export const ImageTo3DExperience = ({
activeTab={activeMode}
onTabChange={(tabId) => setActiveMode(tabId as Mode)}
className="w-fit"
indicatorClassName="bg-primary/25"
indicatorClassName="bg-white/15"
/>
</div>
)}
@ -1195,12 +1201,12 @@ export const ImageTo3DExperience = ({
{previewImage && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/90"
onClick={() => setPreviewImage(null)}
>
<button
type="button"
className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-full bg-black/60 text-white transition-colors hover:bg-black/80"
className="absolute right-4 top-4 flex h-8 w-8 items-center justify-center rounded-[3px] border border-white/15 bg-black/60 text-white transition-colors hover:border-white/30 hover:bg-black"
onClick={() => setPreviewImage(null)}
>
<XIcon className="h-4 w-4" />
@ -1208,7 +1214,7 @@ export const ImageTo3DExperience = ({
<img
src={previewImage}
alt="Preview"
className="max-h-[80vh] max-w-[80vw] rounded-xl object-contain shadow-2xl"
className="max-h-[80vh] max-w-[80vw] border border-white/15 object-contain"
onClick={(e) => e.stopPropagation()}
/>
</div>

View File

@ -0,0 +1,56 @@
import { type ReactNode } from "react";
import { twMerge } from "tailwind-merge";
const CORNERS = [
"top-0 left-0",
"top-0 right-0",
"bottom-0 left-0",
"bottom-0 right-0",
];
interface CreateEmptyStateProps {
title: string;
subtitle: string;
children?: ReactNode;
compact?: boolean;
className?: string;
}
/** A quiet editorial section with a fine border and corner registration marks. */
export function CreateEmptyState({
title,
subtitle,
children,
compact = false,
className,
}: CreateEmptyStateProps) {
return (
<section
className={twMerge(
"create-empty-section relative w-full max-w-3xl px-6 text-left sm:px-10",
compact ? "py-8" : "py-10 sm:py-14",
className,
)}
>
<h1
className={twMerge(
"text-balance font-display leading-[1.05] tracking-[-0.035em] text-ui-ink",
compact ? "text-2xl" : "text-3xl md:text-5xl",
)}
>
{title}
</h1>
<p className="mt-4 max-w-xl text-pretty text-sm leading-relaxed text-white/60 sm:text-base">
{subtitle}
</p>
{children && <div className="mt-6">{children}</div>}
{CORNERS.map((corner) => (
<span
key={corner}
aria-hidden="true"
className={`frame-corner-mark ${corner}`}
/>
))}
</section>
);
}

View File

@ -1,15 +1,16 @@
import { useEffect, useState, type ReactNode } from "react";
import { twMerge } from "tailwind-merge";
import { CreateEmptyState } from "./CreateEmptyState";
// Shared page chrome for the desktop Generate Image / Generate Video pages,
// mirroring the webapp's CreateMediaPageShell: a centered hero over the
// decorative background, and a scrollable generation feed (padded past the
// fixed promptbox) once there is anything to show.
// mirroring the webapp's CreateMediaPageShell: a centered empty-state panel,
// and a scrollable generation feed (padded past the fixed promptbox) once
// there is anything to show.
//
// The hero + background behave like a splash screen: they stay up while the
// feed is still loading (pages remount on tab switches, so this covers the
// reload) and fade out once content arrives. With a genuinely empty library
// they simply stay — they ARE the empty state.
// The empty state (and optional background) behave like a splash screen:
// they stay up while the feed is still loading (pages remount on tab
// switches, so this covers the reload) and fade out once content arrives.
// With a genuinely empty library they simply stay.
const SPLASH_FADE_MS = 700;
@ -17,7 +18,8 @@ interface DesktopCreatePageShellProps {
hasContent: boolean;
emptyStateTitle: string;
emptyStateSubtitle: string;
/** Decorative page background (fixed-position); fades out with the hero. */
/** Optional decorative page background (fixed-position); fades out with
* the empty state. */
background?: ReactNode;
/** Height of the fixed promptbox area, used to pad the feed's bottom. */
bottomOffset: number;
@ -55,11 +57,11 @@ export function DesktopCreatePageShell({
}, [hasContent, splashState]);
return (
<div className="flex h-[calc(100vh-56px)] w-full bg-ui-background">
<div className="flex h-[calc(100vh-56px)] w-full bg-ui-background text-white">
<div className="relative h-full w-full">
{hasContent && (
<div
className="h-full w-full overflow-y-auto pt-4"
className="h-full w-full overflow-y-auto pt-0.5"
style={{ paddingBottom: bottomOffset + 24 }}
>
{listContent}
@ -73,15 +75,14 @@ export function DesktopCreatePageShell({
splashState === "fading" ? "opacity-0" : "opacity-100",
)}
>
<div className="flex h-full w-full flex-col items-center justify-center pb-52">
<div className="relative z-20 flex flex-col items-center justify-center text-center drop-shadow-xl">
<h1 className="text-7xl font-bold text-base-fg">
{emptyStateTitle}
</h1>
<span className="pt-2 text-xl text-base-fg opacity-80">
{emptyStateSubtitle}
</span>
</div>
<div
className="relative z-20 flex h-full w-full items-center justify-center px-6"
style={{ paddingBottom: bottomOffset }}
>
<CreateEmptyState
title={emptyStateTitle}
subtitle={emptyStateSubtitle}
/>
</div>
{background}
</div>
@ -92,7 +93,7 @@ export function DesktopCreatePageShell({
{hasContent && (
<div
aria-hidden
className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-64 bg-gradient-to-t from-ui-background to-transparent"
className="pointer-events-none absolute inset-x-0 bottom-0 z-10 h-48 bg-gradient-to-t from-ui-background to-transparent"
/>
)}

View File

@ -180,7 +180,7 @@ function SelectionDownloadBar({
type="button"
onClick={handleDownload}
disabled={isDownloading || selectedItems.length === 0}
className="flex items-center gap-2 rounded-full bg-ui-controls/60 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-ui-controls/90 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:opacity-60"
className="flex items-center gap-2 border border-white/15 bg-ui-controls/60 px-3 py-1.5 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-white transition-colors hover:bg-ui-controls/90 focus:outline-none focus-visible:ring-2 focus-visible:ring-white/60 disabled:opacity-60"
>
<DynamicIcon
icon={isDownloading ? LoaderCircleIcon : ArrowDownToLineIcon}
@ -226,8 +226,8 @@ function ItemActions({
const buttonClass =
variant === "card"
? "flex h-7 w-7 items-center justify-center rounded-md text-white/85 transition-colors hover:bg-white/15 hover:text-white disabled:opacity-60"
: "flex h-8 w-8 items-center justify-center rounded-md text-white/70 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-60";
? "flex h-7 w-7 items-center justify-center text-white/85 transition-colors hover:bg-white/15 hover:text-white disabled:opacity-60"
: "flex h-8 w-8 items-center justify-center text-white/70 transition-colors hover:bg-white/10 hover:text-white disabled:opacity-60";
const handleRecreate = useCallback(
async (e: React.MouseEvent) => {
@ -305,7 +305,7 @@ function ItemActions({
aria-label="Make Video"
className={buttonClass}
>
<VideoIcon className="text-sm" />
<VideoIcon className="text-sm" />
</button>
</Tooltip>
)}

View File

@ -106,8 +106,8 @@ export const UploadEntryCard = ({
return (
<div
className={twMerge(
"bg-ui-background/60 relative flex h-full flex-col items-center justify-center gap-8 overflow-hidden rounded-2xl border-2 border-dashed border-ui-panel-border p-10 text-center transition-colors",
isDragActive && "border-primary/80 bg-primary/5",
"relative flex h-full flex-col items-center justify-center gap-6 overflow-hidden rounded-[3px] border border-dashed border-white/15 bg-ui-background p-8 text-center transition-colors hover:border-white/40",
isDragActive && "border-white bg-white/10 hover:border-white",
disabled && "pointer-events-none opacity-60",
)}
onDragEnter={handleDragEnter}
@ -124,35 +124,28 @@ export const UploadEntryCard = ({
onChange={handleFileChange}
disabled={disabled}
/>
<div className="flex flex-col items-center gap-6">
<div className="relative">
<div
className={twMerge(
"relative flex h-32 w-32 items-center justify-center rounded-2xl border-2 shadow-xl backdrop-blur-sm",
accentBackgroundClass,
accentBorderClass,
)}
>
<DynamicIcon
icon={icon}
className="text-5xl text-white drop-shadow-lg"
/>
</div>
<div className="flex flex-col items-center gap-4">
<div
className={twMerge(
"flex h-14 w-14 items-center justify-center border",
accentBackgroundClass,
accentBorderClass,
)}
>
<DynamicIcon icon={icon} className="text-xl text-white" />
</div>
<div className="space-y-3">
<h3 className="text-4xl font-bold tracking-tight text-base-fg">
{title}
</h3>
<p className="mx-auto max-w-md text-base leading-relaxed text-base-fg/70">
<div>
<h3 className="text-lg font-semibold text-base-fg">{title}</h3>
<p className="mx-auto mt-1 max-w-md text-sm text-base-fg/60">
{description}
</p>
</div>
<div className="mt-4 flex flex-wrap justify-center gap-4">
<div className="mt-2 flex flex-wrap justify-center gap-2">
<Button
variant="primary"
icon={primaryIcon}
onClick={handlePrimaryClick}
className="px-8 py-3 text-base font-semibold shadow-lg"
className="px-3 py-2"
disabled={disabled}
>
{primaryLabel}
@ -162,7 +155,7 @@ export const UploadEntryCard = ({
variant="action"
icon={secondaryIcon}
onClick={onSecondaryClick}
className="border-2 px-8 py-3 text-base font-semibold"
className="px-3 py-2"
disabled={disabled}
>
{secondaryLabel}
@ -173,7 +166,7 @@ export const UploadEntryCard = ({
variant="action"
icon={tertiaryIcon}
onClick={onTertiaryClick}
className="border-2 px-8 py-3 text-base font-semibold"
className="px-3 py-2"
disabled={disabled}
>
{tertiaryLabel}

View File

@ -24,7 +24,7 @@ export const ConfirmationModal = ({
onClose,
onOk,
okText = "OK",
okColor = "bg-brand-success",
okColor = "",
onCancel,
cancelText = "Cancel",
canHide,
@ -52,7 +52,7 @@ export const ConfirmationModal = ({
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<div className="fixed inset-0 bg-black/40" />
<div className="fixed inset-0 bg-black/80" />
</Transition.Child>
<div className="fixed inset-0 flex w-screen items-center justify-center p-4">
<Transition.Child
@ -64,15 +64,15 @@ export const ConfirmationModal = ({
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-xl border border-ui-panel-border bg-ui-panel p-5 text-left align-middle shadow-xl transition-all">
<Dialog.Panel className="w-full max-w-md transform overflow-hidden border border-white/15 bg-ui-modal p-5 text-left align-middle transition-all">
<Dialog.Title
as="h4"
className="mb-4 text-xl font-bold text-white"
className="mb-4 font-display text-xl tracking-tight text-white"
>
{title}
</Dialog.Title>
<div className="mt-2">{text}</div>
<div className="mt-2 text-sm leading-relaxed text-white/70">{text}</div>
{canHide && (
<div className="mt-2">
<Checkbox id="hide-dialog" label="Do not show this again" />
@ -84,7 +84,7 @@ export const ConfirmationModal = ({
<Button
type="button"
onClick={onCancel}
className="rounded-lg px-3 py-2"
className="px-3 py-2"
variant="secondary"
>
{cancelText}
@ -94,7 +94,7 @@ export const ConfirmationModal = ({
<Button
type="button"
onClick={handleOk}
className={[okColor, "rounded-lg px-3 py-2"].join(" ")}
className={[okColor, "px-3 py-2"].join(" ").trim()}
>
{okText}
</Button>

View File

@ -37,11 +37,11 @@ export const CostModal = ({ credits = 1, onClose }: CostModalProps) => {
transition={{ duration: 0.1, ease: "easeOut" }}
drag
dragMomentum={false}
className="pointer-events-auto z-10 flex w-72 flex-col overflow-hidden rounded-xl border border-ui-panel-border bg-ui-panel shadow-2xl"
className="pointer-events-auto z-10 flex w-72 flex-col overflow-hidden border border-white/15 bg-ui-panel"
>
<div className="bg-ui-panel-header flex cursor-move select-none items-center justify-between border-b border-ui-panel-border px-4 py-3">
<div className="flex items-center gap-2 text-xs font-bold uppercase tracking-wider text-base-fg">
<CoinsIcon className="text-yellow-400" />
<div className="flex cursor-move select-none items-center justify-between border-b border-white/15 px-4 py-3">
<div className="flex items-center gap-2 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg">
<CoinsIcon className="text-primary" />
Cost Breakdown
</div>
<button
@ -53,10 +53,10 @@ export const CostModal = ({ credits = 1, onClose }: CostModalProps) => {
</div>
<div className="space-y-4 bg-ui-panel p-4">
<div className="border-ui-controls-border rounded-lg border bg-ui-controls/50 p-3">
<div className="border border-white/15 bg-white/5 p-3">
<div className="mb-1 flex items-center justify-between">
<span className="text-sm text-base-fg/80">Total Cost</span>
<span className="text-lg font-bold text-base-fg">
<span className="text-lg font-semibold tabular-nums tracking-tight text-base-fg">
{credits} Credits
</span>
</div>
@ -66,7 +66,7 @@ export const CostModal = ({ credits = 1, onClose }: CostModalProps) => {
</div>
<div className="space-y-1">
<label className="text-xs font-medium text-base-fg/80">
<label className="font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
Currency
</label>
<Select
@ -77,7 +77,7 @@ export const CostModal = ({ credits = 1, onClose }: CostModalProps) => {
/>
</div>
<div className="mt-2 border-t border-ui-panel-border pt-3 text-center text-[10px] text-base-fg/40">
<div className="mt-2 border-t border-white/15 pt-3 text-center font-mono text-[10px] uppercase tracking-[0.12em] text-base-fg/40">
1 Credit = $0.01 USD
</div>
</div>

View File

@ -84,7 +84,7 @@ export const UploadFilesMedia = ({
<h6 className="z-10 text-red">{assetFile.error}</h6>
)}
<div className="relative m-auto aspect-square w-full overflow-hidden rounded-lg bg-brand-secondary">
<div className="relative m-auto aspect-square w-full overflow-hidden border border-white/15 bg-ui-controls">
{!assetFile.value && (
<h6 className="absolute left-0 top-1/2 -mt-5 w-full text-center">
File Preview

View File

@ -85,7 +85,7 @@ export const UploadImageMedia = ({
<H6 className="z-10 text-red"> {assetFile.error} </H6>
)}
<div className="relative m-auto aspect-square w-full overflow-hidden rounded-lg bg-brand-secondary">
<div className="relative m-auto aspect-square w-full overflow-hidden border border-white/15 bg-ui-controls">
{!assetFile.value && (
<H6 className="absolute left-0 top-1/2 -mt-5 w-full text-center">
File Preview

View File

@ -61,7 +61,7 @@ export function UploadImageMediaModal({
return (
<>
<LoadingDots className="mb-1 bg-transparent" />
<div className="w-100 text-center opacity-50">Uploading...</div>
<div className="hud-label w-full text-center text-base-fg/50">Uploading...</div>
</>
);
case UploaderStates.success:

View File

@ -59,7 +59,7 @@ export function UploadModalMedia({
return (
<>
<LoadingDots className="mb-1 bg-transparent" />
<div className="w-100 text-center opacity-50">Uploading...</div>
<div className="hud-label w-full text-center text-base-fg/50">Uploading...</div>
</>
);
case UploaderStates.success:

View File

@ -20,14 +20,14 @@ export function ErrorDialog() {
<Modal
title={errorDialogTitle}
titleIcon={TriangleAlertIcon}
titleIconClassName="text-brand-primary"
titleIconClassName="text-red-400"
isOpen={showErrorDialog}
onClose={() => setShowErrorDialog(false)}
showClose={false}
>
<div>
{errorDialogMessage}
<div className="flex justify-end">
<div className="mt-4 flex justify-end">
<Button
type="button"
onClick={() => setShowErrorDialog(false)}

View File

@ -3,8 +3,10 @@ import { twMerge } from "tailwind-merge";
import {
useGenerateApps,
useEditApps,
getAppCardPalette,
getBadgeStyles,
goToApp,
type FullAppItem,
} from "~/config/appMenu";
export const AppsQuickMenu = () => {
@ -12,101 +14,68 @@ export const AppsQuickMenu = () => {
const editApps = useEditApps();
return (
<div className="grid w-[680px] grid-cols-2 gap-3">
<div>
<h3 className="mb-2 px-2 text-xs font-semibold opacity-50">Create</h3>
<div className="space-y-0.5">
{generateApps.map((app) => (
<button
key={app.id}
onClick={() => goToApp(app.action)}
disabled={!app.action}
className={twMerge(
"group flex w-full items-center gap-3 rounded-md px-2 py-2 text-left transition-colors",
app.action
? "cursor-pointer hover:bg-base-fg/10"
: "cursor-default opacity-60",
)}
>
<div
className={twMerge(
"flex h-8 w-8 shrink-0 items-center justify-center rounded-md transition-colors",
app.color || "bg-ui-panel",
)}
>
<DynamicIcon icon={app.icon} className="text-sm" />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<div className="truncate text-[13px] font-medium">
{app.label}
</div>
{app.badge && (
<span
className={twMerge(
"shrink-0 rounded-full px-2 py-1 text-[9px] font-bold uppercase tracking-wider",
getBadgeStyles(app.badge),
)}
>
{app.badge}
</span>
)}
</div>
<div className="truncate text-[11px] opacity-60">
{app.description}
</div>
</div>
</button>
))}
</div>
</div>
<div>
<h3 className="mb-2 px-2 text-xs font-semibold opacity-50">Edit</h3>
<div className="space-y-0.5">
{editApps.map((app) => (
<button
key={app.id}
onClick={() => goToApp(app.action)}
disabled={!app.action}
className={twMerge(
"group flex w-full items-center gap-3 rounded-md px-2 py-2 text-left transition-colors",
app.action
? "cursor-pointer hover:bg-base-fg/10"
: "cursor-default opacity-60",
)}
>
<div
className={twMerge(
"flex h-8 w-8 shrink-0 items-center justify-center rounded-md transition-colors",
app.color || "bg-ui-panel",
)}
>
<DynamicIcon icon={app.icon} className="text-sm" />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<div className="truncate text-[13px] font-medium">
{app.label}
</div>
{app.badge && (
<span
className={twMerge(
"shrink-0 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider",
getBadgeStyles(app.badge),
)}
>
{app.badge}
</span>
)}
</div>
<div className="truncate text-[11px] opacity-60">
{app.description}
</div>
</div>
</button>
))}
</div>
</div>
<AppsQuickMenuSection title="Create" apps={generateApps} />
<AppsQuickMenuSection title="Edit" apps={editApps} />
</div>
);
};
const AppsQuickMenuSection = ({
title,
apps,
}: {
title: string;
apps: FullAppItem[];
}) => (
<div>
<h3 className="hud-label mb-2 px-2 text-base-fg/50">{title}</h3>
<div className="space-y-0.5">
{apps.map((app) => {
const palette = getAppCardPalette(app.id);
return (
<button
key={app.id}
onClick={() => goToApp(app.action)}
disabled={!app.action}
className={twMerge(
"group flex w-full items-center gap-3 rounded-[3px] px-2 py-2 text-left transition-colors",
app.action
? "cursor-pointer hover:bg-white/[0.08]"
: "cursor-default opacity-60",
)}
>
<div
className={twMerge(
"flex h-8 w-8 shrink-0 items-center justify-center border transition-colors",
palette.iconBg,
palette.iconColor,
)}
>
<DynamicIcon icon={app.icon} className="text-sm" />
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<div className="truncate text-[13px] font-medium">
{app.label}
</div>
{app.badge && (
<span
className={twMerge(
"shrink-0 border px-1.5 py-0.5 font-mono text-[9px] font-semibold uppercase leading-none tracking-[0.12em]",
getBadgeStyles(app.badge),
)}
>
{app.badge}
</span>
)}
</div>
<div className="truncate text-[11px] text-base-fg/60">
{app.description}
</div>
</div>
</button>
);
})}
</div>
</div>
);

View File

@ -1,7 +1,6 @@
import { useSignals } from "@preact/signals-react/runtime";
import { AUTH_STATUS } from "~/enums";
import { authentication } from "~/signals";
import { Button } from "@storyteller/ui-button";
// import ProfileDropdown from "./ProfileDropdown";
export const AuthButtons = ({
@ -19,15 +18,14 @@ export const AuthButtons = ({
return (
<>
<div className="flex items-center gap-2">
<span className="text-white/20">|</span>
<Button
className="h-[38px]"
<button
className="flex h-8 items-center gap-1.5 rounded-[3px] bg-white px-3.5 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-black transition-colors hover:bg-white/80"
onClick={() => {
loginSignUpPressed();
}}
>
Login / Sign Up
</Button>
</button>
</div>
</>
);

View File

@ -56,20 +56,20 @@ export default function ProfileDropdown() {
>
<Menu.Items
static
className="absolute right-[-5px] mt-2.5 w-36 overflow-hidden rounded-lg bg-brand-secondary shadow-lg focus:outline-none"
className="absolute right-0 z-50 mt-2 w-48 origin-top-right overflow-hidden rounded-[3px] border border-white/15 bg-[#101014] focus:outline-none"
>
<Menu.Item key={0}>
{({ active }) => (
<a
className={twMerge(
"duration-50 group flex w-full items-center gap-2 bg-action/60 px-3 py-[10px] text-start text-sm font-medium text-white transition-all",
active && "bg-action-500/80",
"group flex w-full items-center gap-2 px-4 py-2 text-start text-sm text-white/70 transition-colors",
active && "bg-white/10",
)}
href={profileUrl}
target="_blank"
rel="noreferrer"
>
<UserIcon />
<UserIcon className="text-[11px] text-white/50" />
My Profile
</a>
)}
@ -79,12 +79,15 @@ export default function ProfileDropdown() {
{({ active }) => (
<button
className={twMerge(
"duration-50 group flex w-full items-center gap-2 bg-action/60 px-3 py-[10px] text-start text-sm font-medium text-white transition-all",
active && "bg-action-500/80",
"group flex w-full items-center gap-2 px-4 py-2 text-start text-sm text-white/70 transition-colors",
active && "bg-white/10",
)}
onClick={() => option.onClick()}
>
<DynamicIcon icon={option.icon} />
<DynamicIcon
icon={option.icon}
className="text-[11px] text-white/50"
/>
{option.label}
</button>
)}

View File

@ -1,12 +1,11 @@
import { useState } from "react";
import { twMerge } from "tailwind-merge";
import { useSignals } from "@preact/signals-react/runtime";
import { LoaderCircleIcon, PencilIcon } from "lucide-react";
import { ChevronRightIcon, LoaderCircleIcon, PencilIcon } from "lucide-react";
import { scene, signalScene, authentication } from "~/signals";
import { usePageSceneStore } from "@storyteller/ui-pagescene";
import { Input } from "@storyteller/ui-input";
import { MediaFilesApi } from "~/Classes/ApiManager/MediaFilesApi";
import { getCreatorIcon, ModelCreator } from "@storyteller/model-list";
interface Props {
pageName: string;
@ -95,27 +94,29 @@ export const SceneTitleInput = ({ pageName }: Props) => {
data-tauri-drag-region
>
{!showInput && (
<div className="flex items-center gap-2.5" data-tauri-drag-region>
{getCreatorIcon(
ModelCreator.ArtCraft,
"h-5 w-5 icon-auto-contrast opacity-60",
)}
<span className="text-nowrap opacity-60">{pageName}</span>
<span className="opacity-60">/</span>
<div className="flex items-center gap-1.5" data-tauri-drag-region>
<span
className="hud-label text-nowrap text-base-fg/70"
data-tauri-drag-region
>
{pageName}
</span>
<ChevronRightIcon
aria-hidden="true"
className="h-3 w-3 shrink-0 text-base-fg/50"
/>
{isSceneOwner ? (
<button
className="ml-0.5 rounded-md px-2 py-1 transition-all hover:cursor-text hover:bg-white/[8%]"
className="flex max-w-[280px] items-center border border-transparent px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:cursor-text hover:bg-white/10"
onClick={handleShowInput}
data-tauri-drag-region="false"
>
{scene.value.title || ""}
<PencilIcon
className="ml-2 text-sm opacity-50" />
<span className="truncate">{scene.value.title || ""}</span>
<PencilIcon className="ml-2 shrink-0 text-sm opacity-50" />
</button>
) : (
<div className="ml-0.5 rounded-md px-2 py-1">
<div className="max-w-[280px] truncate border border-transparent px-3 py-1.5 text-sm font-semibold text-white/80">
{scene.value.title || ""}
</div>
)}
@ -128,8 +129,8 @@ export const SceneTitleInput = ({ pageName }: Props) => {
disabled={scene.value.ownerToken !== userInfo.value?.user_token}
className="w-[420px]"
inputClassName={twMerge(
"text-center h-8 focus:outline-brand-primary",
isSaving && "outline-brand-secondary",
"text-center h-[34px] text-sm font-semibold focus:outline-white/60",
isSaving && "outline-white/30",
)}
isError={!isValid}
value={scene.value.title || ""}
@ -152,7 +153,9 @@ export const SceneTitleInput = ({ pageName }: Props) => {
</div>
)}
{isSaving && <LoaderCircleIcon className="animate-spin" />}
{isSaving && (
<LoaderCircleIcon className="shrink-0 animate-spin text-sm opacity-70" />
)}
</div>
);
};

View File

@ -41,6 +41,7 @@ import { coverImageCache } from "~/pages/PageImageTo3DObject/ImageTo3DStore";
import { useCreditsState } from "@storyteller/credits";
import { getMetaForTask, cleanupOldEntries } from "./taskEnqueueMeta";
import { twMerge } from "tailwind-merge";
import dayjs from "dayjs";
type InProgressTask = {
id: string;
@ -159,7 +160,7 @@ const CopyPromptButton = ({ prompt }: { prompt: string }) => {
delay={300}
>
<button
className="flex h-6 w-6 items-center justify-center rounded-full text-base-fg/60 hover:bg-ui-controls"
className="flex h-6 w-6 items-center justify-center text-base-fg/60 hover:bg-ui-controls"
aria-label="Copy prompt"
onClick={(e) => {
e.stopPropagation();
@ -195,7 +196,7 @@ const InProgressCard = ({
const hasRefImages = task.refImageUrls && task.refImageUrls.length > 0;
const thumbnailContent = hasRefImages ? (
<div className="relative h-[86px] w-[86px] shrink-0 overflow-hidden rounded">
<div className="relative h-[72px] w-[72px] shrink-0 overflow-hidden">
<img
src={task.refImageUrls![0]}
alt="Reference"
@ -212,13 +213,13 @@ const InProgressCard = ({
size="lg" />
</div>
{task.refImageUrls!.length > 1 && (
<div className="absolute bottom-0.5 right-0.5 rounded bg-black/60 px-1 text-[9px] text-white/80">
<div className="absolute bottom-0.5 right-0.5 bg-black/60 px-1 text-[9px] text-white/80">
+{task.refImageUrls!.length - 1}
</div>
)}
</div>
) : (
<div className="flex h-[86px] w-[86px] shrink-0 items-center justify-center overflow-hidden rounded bg-ui-controls">
<div className="flex h-[72px] w-[72px] shrink-0 items-center justify-center overflow-hidden bg-ui-controls">
<LoaderCircleIcon
className="animate-spin text-base-fg/60"
@ -227,7 +228,7 @@ const InProgressCard = ({
);
return (
<div className="rounded-md p-2 transition-colors hover:bg-ui-controls/40">
<div className="p-2 transition-colors hover:bg-ui-controls/40">
<div className="flex items-center gap-2.5">
{thumbnailContent}
<div className="min-w-0 flex-1">
@ -239,7 +240,7 @@ const InProgressCard = ({
content="Seedance 2.0 is in Early Alpha. Generations may be slow and may experience outages."
position="top"
strategy="fixed"
className="w-[200px] text-wrap bg-yellow-400/60 backdrop-blur-3xl"
className="w-[200px] text-wrap bg-yellow-400/60"
zIndex={50}
delay={100}
>
@ -249,7 +250,7 @@ const InProgressCard = ({
</Tooltip>
)}
</div>
<div className="ml-2 shrink-0 text-[11px] tabular-nums text-base-fg/60">
<div className="ml-2 shrink-0 text-xs tabular-nums text-base-fg/60">
{progressPercent}%
</div>
</div>
@ -259,9 +260,9 @@ const InProgressCard = ({
</div>
)}
<div className="mt-1.5 flex items-center gap-2">
<div className="h-1.5 min-w-0 flex-1 rounded bg-ui-controls">
<div className="h-1.5 min-w-0 flex-1 bg-ui-controls">
<div
className="h-1.5 rounded bg-brand-primary-400"
className="h-1.5 bg-white"
style={{
width: `${Math.max(0, Math.min(100, task.progress))}%`,
}}
@ -269,7 +270,7 @@ const InProgressCard = ({
</div>
</div>
{timeLabel && (
<div className="mt-1 text-[11px] text-base-fg/50">{timeLabel}</div>
<div className="mt-1 text-xs text-base-fg/50">{timeLabel}</div>
)}
{task.prompt && <PromptLine prompt={task.prompt} className="mt-0" />}
</div>
@ -277,7 +278,7 @@ const InProgressCard = ({
{task.prompt && <CopyPromptButton prompt={task.prompt} />}
{onDismiss && (
<button
className="flex h-6 w-6 items-center justify-center rounded-full text-base-fg/60 hover:bg-ui-controls"
className="flex h-6 w-6 items-center justify-center text-base-fg/60 hover:bg-ui-controls"
aria-label="Dismiss"
onClick={(e) => {
e.stopPropagation();
@ -304,12 +305,12 @@ const CompletedCard = ({
}) => {
return (
<div
className="flex cursor-pointer items-center gap-2.5 rounded-md p-2 transition-colors hover:bg-ui-controls/40"
className="flex cursor-pointer items-center gap-2.5 p-2 transition-colors hover:bg-ui-controls/40"
onClick={onClick}
role={onClick ? "button" : undefined}
tabIndex={onClick ? 0 : -1}
>
<div className="h-[86px] w-[86px] shrink-0 overflow-hidden rounded bg-ui-controls">
<div className="h-[72px] w-[72px] shrink-0 overflow-hidden bg-ui-controls">
{task.thumbnailUrl ? (
<img
src={task.thumbnailUrl}
@ -342,7 +343,7 @@ const CompletedCard = ({
)}
{task.completedAt && (
<div className="text-xs text-base-fg opacity-60">
{task.completedAt.toISOString()}
{dayjs(task.completedAt).format("MMM D, h:mm A")}
</div>
)}
{task.prompt && <PromptLine prompt={task.prompt} />}
@ -351,7 +352,7 @@ const CompletedCard = ({
{task.prompt && <CopyPromptButton prompt={task.prompt} />}
{onDismiss && (
<button
className="flex h-6 w-6 items-center justify-center rounded-full text-base-fg/60 hover:bg-ui-controls"
className="flex h-6 w-6 items-center justify-center text-base-fg/60 hover:bg-ui-controls"
aria-label="Dismiss"
onClick={(e) => {
e.stopPropagation();
@ -398,7 +399,7 @@ const FailedCard = ({
const hasRefImages = task.refImageUrls && task.refImageUrls.length > 0;
const thumbnailContent = hasRefImages ? (
<div className="relative h-[86px] w-[86px] shrink-0 overflow-hidden rounded">
<div className="relative h-[72px] w-[72px] shrink-0 overflow-hidden">
<img
src={task.refImageUrls![0]}
alt="Reference"
@ -415,13 +416,13 @@ const FailedCard = ({
size="lg" />
</div>
{task.refImageUrls!.length > 1 && (
<div className="absolute bottom-0.5 right-0.5 rounded bg-black/60 px-1 text-[9px] text-white/80">
<div className="absolute bottom-0.5 right-0.5 bg-black/60 px-1 text-[9px] text-white/80">
+{task.refImageUrls!.length - 1}
</div>
)}
</div>
) : (
<div className="flex h-[86px] w-[86px] shrink-0 items-center justify-center overflow-hidden rounded bg-red-500/10">
<div className="flex h-[72px] w-[72px] shrink-0 items-center justify-center overflow-hidden bg-red-500/10">
<CircleAlertIcon
className="text-red-400"
@ -430,7 +431,7 @@ const FailedCard = ({
);
return (
<div className="rounded-md p-2 transition-colors hover:bg-ui-controls/40">
<div className="p-2 transition-colors hover:bg-ui-controls/40">
<div className="flex items-center gap-2.5">
{thumbnailContent}
<div className="min-w-0 flex-1">
@ -445,7 +446,7 @@ const FailedCard = ({
</div>
)}
<div className="mt-1 flex min-w-0 items-center gap-1.5 overflow-hidden">
<span className="shrink-0 rounded bg-red-500/15 px-1.5 py-0 text-[11px] font-medium text-red-400">
<span className="shrink-0 bg-red-500/15 px-1.5 py-0 text-[11px] font-medium text-red-400">
{statusLabel}
</span>
{task.failureReason && (
@ -478,13 +479,18 @@ const FailedCard = ({
</div>
)}
</div>
{task.failedAt && (
<div className="mt-0.5 text-[11px] text-base-fg/40">
{dayjs(task.failedAt).format("MMM D, h:mm A")}
</div>
)}
{task.prompt && <PromptLine prompt={task.prompt} />}
</div>
<div className="ml-auto flex shrink-0 items-center gap-1">
{task.prompt && <CopyPromptButton prompt={task.prompt} />}
{onDismiss && (
<button
className="flex h-6 w-6 items-center justify-center rounded-full text-base-fg/60 hover:bg-ui-controls"
className="flex h-6 w-6 items-center justify-center text-base-fg/60 hover:bg-ui-controls"
aria-label="Dismiss"
onClick={(e) => {
e.stopPropagation();
@ -1002,23 +1008,21 @@ export const TaskQueue = () => {
<Tooltip content="Task Queue" position="bottom" closeOnClick={true}>
<div className="relative">
{badgeCount > 0 && (
<div className="absolute -right-1 -top-1 z-20 flex h-[17px] w-[17px] items-center justify-center rounded-full bg-brand-primary-400 text-[13px] font-medium text-white">
<div className="absolute -right-1 -top-1 z-20 flex h-[15px] min-w-[15px] items-center justify-center bg-white px-1 font-mono text-[10px] font-semibold text-black ring-2 ring-[#0b0b0c]">
{badgeCount}
</div>
)}
<PopoverMenu
mode="default"
buttonClassName="h-[34px] w-[34px] !p-0 relative"
panelClassName="w-[400px] p-2 bg-ui-panel mt-2.5"
buttonClassName="h-8 w-8 !p-0 relative bg-transparent hover:bg-white/10 border border-white/15 hover:border-white/30 text-white/80 rounded-[3px] shadow-none"
panelClassName="w-[400px] p-2 bg-[#101014] border border-white/15 mt-2 rounded-[3px]"
position="bottom"
align="end"
triggerIcon={
inProgressCount > 0 ? (
<LoaderCircleIcon
className="animate-spin" />
<LoaderCircleIcon className="animate-spin text-[11px]" />
) : (
<ListChecksIcon />
<ListChecksIcon className="text-[11px]" />
)
}
onOpenChange={handleOpenChange}
@ -1037,7 +1041,7 @@ export const TaskQueue = () => {
<div>
{inProgress.length > 0 && (
<div className="mb-4">
<div className="mb-1 px-1 text-xs uppercase tracking-wide text-base-fg/50">
<div className="mb-1 px-1 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/50">
In Progress
</div>
{inProgress.map((t) => (
@ -1056,7 +1060,7 @@ export const TaskQueue = () => {
{failed.length > 0 && (
<div className="mb-4">
<div className="mb-1 flex items-center justify-between px-1">
<div className="text-xs font-semibold uppercase tracking-wide text-red-400/70">
<div className="font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-red-400/70">
Failed
</div>
<button
@ -1081,7 +1085,7 @@ export const TaskQueue = () => {
{completed.length > 0 && (
<div>
<div className="mb-1 flex items-center justify-between px-1">
<div className="text-xs font-semibold uppercase tracking-wide text-base-fg/50">
<div className="font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/50">
Completed
</div>
<button
@ -1159,7 +1163,7 @@ export const TaskQueue = () => {
showClose={false}
>
<div className="flex h-full flex-col">
<div className="rounded-t-xl border-ui-panel-border bg-ui-panel">
<div className="border-b border-ui-panel-border bg-ui-panel">
<div className="flex items-center justify-between p-3">
<h2 className="text-lg font-semibold">Task Queue</h2>
<div className="flex items-center gap-2">
@ -1207,7 +1211,7 @@ export const TaskQueue = () => {
<div>
{inProgress.length > 0 && (
<div className="mb-4">
<div className="mb-2 px-1 text-xs uppercase tracking-wide text-base-fg/50">
<div className="mb-1 px-1 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/50">
In Progress
</div>
{inProgress.map((t) => (
@ -1223,7 +1227,7 @@ export const TaskQueue = () => {
)}
{failed.length > 0 && (
<div className="mb-4">
<div className="mb-2 px-1 text-xs uppercase tracking-wide text-red-400/70">
<div className="mb-1 px-1 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-red-400/70">
Failed
</div>
{failed.map((t) => (
@ -1237,7 +1241,7 @@ export const TaskQueue = () => {
)}
{completed.length > 0 && (
<div>
<div className="mb-2 px-1 text-xs uppercase tracking-wide text-base-fg/50">
<div className="mb-1 px-1 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/50">
Completed
</div>
{completed.map((t) => (

View File

@ -1,8 +1,7 @@
import { CalculatorIcon, CheckIcon, CircleAlertIcon, CoinsIcon, GemIcon, HouseIcon, ImagesIcon, MinusIcon, PictureInPicture2Icon, SettingsIcon, SquareIcon, XIcon } from "lucide-react";
import { CalculatorIcon, CheckIcon, ChevronRightIcon, CircleAlertIcon, CoinsIcon, GemIcon, HouseIcon, ImagesIcon, MinusIcon, PictureInPicture2Icon, SettingsIcon, SquareIcon, XIcon } from "lucide-react";
import { DynamicIcon } from "@storyteller/icons";
import { signal } from "@preact/signals-react";
import { useSignals } from "@preact/signals-react/runtime";
import { getCreatorIcon, ModelCreator } from "@storyteller/model-list";
import { useCreditsState, type CreditsIconStatus } from "@storyteller/credits";
import { gtagEvent } from "@storyteller/google-analytics";
import { ProviderBillingModal } from "@storyteller/provider-billing-modal";
@ -42,7 +41,7 @@ import {
} from "@storyteller/ui-generation-list";
import { SettingsModal } from "@storyteller/ui-settings-modal";
import { Tooltip } from "@storyteller/ui-tooltip";
import { useEffect, useRef, useState } from "react";
import { Fragment, useEffect, useRef, useState } from "react";
import { APP_DESCRIPTORS, goToApp } from "~/config/appMenu";
import {
applyMakeVideoFromImage,
@ -167,10 +166,10 @@ const CreditsCoinWithStatus = ({
}
>
<span className="relative inline-flex">
<CoinsIcon className="text-primary" />
<CoinsIcon className="text-[11px] text-primary" />
{showBadge && (
<span
className={`absolute -right-1.5 -top-1.5 flex h-3 w-3 items-center justify-center rounded-full ring-1 ring-ui-background ${badgeColorClass}`}
className={`absolute -right-1.5 -top-1.5 flex h-3 w-3 items-center justify-center ring-1 ring-ui-panel ${badgeColorClass}`}
>
<DynamicIcon icon={badgeIconDef} className="text-[7px]" />
</span>
@ -347,40 +346,50 @@ export const TopBar = ({ pageName }: Props) => {
}
};
const getPageTitle = (): string => {
const getPageCrumbs = (): string[] => {
switch (tabStore.activeTabId) {
case "2D":
return "Canvas";
return ["Studio", "Canvas"];
case "3D":
return "3D Editor";
return ["Studio", "3D Editor"];
case "IMAGE":
return "Create Image";
return ["Create", "Image"];
case "VIDEO":
return "Create Video";
return ["Create", "Video"];
case "AUDIO":
return "Create Audio";
return ["Create", "Audio"];
case "EDIT":
return "Edit Image";
return ["Studio", "Edit Image"];
case "VIDEO_FRAME_EXTRACTOR":
return "Video Frame Extractor";
return ["Studio", "Frame Extractor"];
case "VIDEO_WATERMARK_REMOVAL":
return "Video Watermark Remover";
return ["Studio", "Video Watermark Remover"];
case "IMAGE_WATERMARK_REMOVAL":
return "Image Watermark Remover";
return ["Studio", "Image Watermark Remover"];
case "IMAGE_TO_3D_OBJECT":
return "Image to 3D Object";
return ["Create", "3D Object"];
case "IMAGE_TO_3D_WORLD":
return "Image to 3D World";
case "APPS":
return "ArtCraft";
return ["Create", "3D World"];
case "REMOVE_BACKGROUND":
return ["Studio", "Remove Background"];
case "ANGLES":
return ["Create", "Angles"];
case "STORYBOARD":
return ["Create", "Storyboard"];
case "BACKGROUND_CHANGE":
return "Background Change";
return ["Studio", "Background Change"];
case "VIDEO_EDITOR":
return ["Studio", "Edit Video"];
case "MOODBOARD":
return ["Studio", "Moodboard"];
case "APPS":
return ["Home"];
default:
return "Artcraft";
return ["ArtCraft"];
}
};
const pageTitle = getPageTitle();
const pageCrumbs = getPageCrumbs();
const { toggleModal: toggleSubscriptionModal } = usePricingModalStore();
const { toggleModal: toggleCreditsModal } = useCreditsModalStore();
@ -418,7 +427,7 @@ export const TopBar = ({ pageName }: Props) => {
return (
<>
<header
className="fixed left-0 top-0 z-[60] w-full border-b border-ui-panel-border bg-ui-background"
className="fixed left-0 top-0 z-[60] w-full border-b border-ui-border bg-ui-panel"
data-tauri-drag-region
>
<nav
@ -479,27 +488,47 @@ export const TopBar = ({ pageName }: Props) => {
</div>
<div
className={`${tabStore.activeTabId === "3D" ? "no-drag" : ""} flex items-center justify-center gap-2 font-medium`}
className={`${tabStore.activeTabId === "3D" ? "no-drag" : ""} flex min-w-0 items-center justify-center gap-2 font-medium`}
data-tauri-drag-region
>
{tabStore.activeTabId === "3D" ? (
<SceneTitleInput pageName={pageName} />
) : (
<h1
className="flex items-center gap-2.5 text-base-fg"
className="hud-label flex min-w-0 items-center gap-1.5 text-base-fg/70"
data-tauri-drag-region
>
{getCreatorIcon(
ModelCreator.ArtCraft,
"h-5 w-5 icon-auto-contrast opacity-50",
)}
{pageTitle}
{pageCrumbs.map((crumb, i) => {
const isLast = i === pageCrumbs.length - 1;
return (
<Fragment key={`${crumb}-${i}`}>
{i > 0 && (
<ChevronRightIcon
aria-hidden="true"
className="h-3 w-3 shrink-0 text-base-fg/50"
data-tauri-drag-region
/>
)}
<span
className={
isLast
? "truncate bg-ui-ink px-1.5 py-1 text-ui-panel"
: "truncate"
}
aria-current={isLast ? "page" : undefined}
data-tauri-drag-region
>
{crumb}
</span>
</Fragment>
);
})}
</h1>
)}
</div>
<div className="flex justify-end gap-2" data-tauri-drag-region>
<div className="no-drag flex items-center gap-1.5">
<div className="no-drag flex items-center gap-1.5 sm:gap-2">
{(tabStore.activeTabId === "IMAGE" ||
tabStore.activeTabId === "VIDEO") && <GallerySelectToggle />}
{tabStore.activeTabId === "VIDEO" && <GalleryAutoplayToggle />}
@ -508,26 +537,26 @@ export const TopBar = ({ pageName }: Props) => {
tabStore.activeTabId === "AUDIO") && <GalleryViewToggle />}
<PopoverMenu
position="bottom"
align="center"
align="end"
triggerIcon={
<CreditsCoinWithStatus iconStatus={creditsIconStatus} />
}
triggerLabel={
<span className="whitespace-nowrap text-sm font-medium">
{sumTotalCredits} Credits
{sumTotalCredits.toLocaleString()}
</span>
}
buttonClassName="h-[30px] px-2 ps-1.5 bg-transparent hover:bg-ui-controls/30 border-0 shadow-none"
panelClassName="mt-3 bg-ui-panel border border-ui-panel-border text-base-fg"
buttonClassName="h-8 px-3 ps-2.5 bg-transparent hover:bg-white/10 border border-white/15 hover:border-white/30 shadow-none text-white/80 rounded-[3px] gap-1.5"
panelClassName="mt-2 bg-[#101014] border border-white/15 text-white rounded-[3px]"
>
{(close) => (
<div className="w-72 p-2.5 text-base-fg">
<div className="w-72 p-3 text-white">
<div className="mb-2 flex items-center justify-between">
<span className="flex items-center gap-1.5 text-sm font-medium text-base-fg/80">
<span className="text-sm font-medium text-white/70">
Your credit balance
</span>
<button
className="text-sm font-medium text-primary-400 transition-all hover:text-primary-300"
className="text-sm font-medium text-primary transition-colors hover:text-primary-300"
onClick={() => {
close();
toggleCreditsModal();
@ -536,15 +565,13 @@ export const TopBar = ({ pageName }: Props) => {
Buy credits
</button>
</div>
<div className="flex items-center gap-2 text-4xl font-bold text-base-fg">
<CoinsIcon
className="text-2xl text-primary" />
{sumTotalCredits}
<div className="flex items-center gap-2 text-3xl font-semibold tracking-tight text-white">
<CoinsIcon className="text-xl text-primary" />
{sumTotalCredits.toLocaleString()}
</div>
<button
className="mt-2 flex items-center gap-1.5 text-xs text-base-fg/50 transition-colors hover:text-primary"
className="mt-2 flex items-center gap-1.5 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-white/50 transition-colors hover:text-white"
onClick={() => {
close();
useCostBreakdownModalStore.getState().openModal();
@ -556,7 +583,7 @@ export const TopBar = ({ pageName }: Props) => {
<div className="mt-3 flex gap-2">
<Button
variant="action"
variant="secondary"
className="h-9 grow"
onClick={() => {
close();
@ -586,20 +613,35 @@ export const TopBar = ({ pageName }: Props) => {
variant="primary"
icon={GemIcon}
onClick={toggleSubscriptionModal}
className="transition-all duration-300"
className="h-8 px-3"
>
Upgrade
</Button>
)}
<UploadImagesButton className="h-[34px] w-[34px]" />
<TaskQueue />
<button
type="button"
onClick={handleOpenGalleryModal}
aria-label="My Library"
className="flex h-8 items-center gap-1.5 rounded-[3px] border border-white/15 px-3 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-white/80 transition-colors hover:border-white/30 hover:bg-white/10"
>
<ImagesIcon className="text-[11px]" />
<span className="hidden whitespace-nowrap xl:block">
My Library
</span>
</button>
<UploadImagesButton />
<Tooltip content="Settings" position="bottom" delay={300}>
<Button
aria-label="Settings"
variant="secondary"
icon={SettingsIcon}
iconClassName="h-5 w-5 shrink-0"
className="h-[34px] w-[34px] p-0"
iconClassName="h-4 w-4 shrink-0"
className="h-8 w-8 border-white/15 bg-transparent p-0 text-white/80 hover:border-white/30 hover:bg-white/10"
onClick={() => {
setSettingsSection("general");
setIsSettingsModalOpen(true);
@ -607,19 +649,6 @@ export const TopBar = ({ pageName }: Props) => {
}}
/>
</Tooltip>
<Button
variant="secondary"
icon={ImagesIcon}
onClick={handleOpenGalleryModal}
>
<span className="hidden whitespace-nowrap text-base-fg xl:block">
My Library
</span>
</Button>
{/* <Activity /> */}
<TaskQueue />
</div>
<div className="no-drag">
@ -630,14 +659,14 @@ export const TopBar = ({ pageName }: Props) => {
<div className="no-drag flex items-center">
<Button
variant="secondary"
className="h-[32px] w-[44px] rounded-none border-0 bg-transparent text-base-fg opacity-70 shadow-none hover:bg-ui-controls/20 hover:opacity-100"
className="h-[32px] w-[44px] rounded-none border-0 bg-transparent p-0 text-base-fg opacity-70 shadow-none hover:bg-white/10 hover:opacity-100"
onClick={minimize}
>
<MinusIcon className="text-xs" />
<MinusIcon className="text-xs" />
</Button>
<Button
variant="secondary"
className="h-[32px] w-[44px] rounded-none border-0 bg-transparent text-base-fg opacity-70 shadow-none hover:bg-ui-controls/20 hover:opacity-100"
className="h-[32px] w-[44px] rounded-none border-0 bg-transparent p-0 text-base-fg opacity-70 shadow-none hover:bg-white/10 hover:opacity-100"
onClick={toggleMaximize}
>
<DynamicIcon
@ -647,10 +676,10 @@ export const TopBar = ({ pageName }: Props) => {
</Button>
<Button
variant="secondary"
className="h-[32px] w-[44px] rounded-none border-0 bg-transparent text-base-fg opacity-70 shadow-none hover:bg-red/10 hover:text-red"
className="h-[32px] w-[44px] rounded-none border-0 bg-transparent p-0 text-base-fg opacity-70 shadow-none hover:bg-red hover:text-white hover:opacity-100"
onClick={close}
>
<XIcon className="text-lg" />
<XIcon className="text-lg" />
</Button>
</div>
)}

View File

@ -18,8 +18,11 @@ export const UploadImagesButton = ({ className }: Props) => {
<Button
variant="secondary"
icon={UploadIcon}
iconClassName="h-5 w-5 shrink-0"
className={twMerge("h-[38px] w-[38px] p-0", className)}
iconClassName="h-4 w-4 shrink-0"
className={twMerge(
"h-8 w-8 rounded-[3px] border border-white/15 bg-transparent p-0 text-white/80 shadow-none hover:border-white/30 hover:bg-white/10",
className,
)}
onClick={() => setIsOpen(true)}
/>
</Tooltip>

View File

@ -83,98 +83,122 @@ export interface FullAppItem {
}
// Per-app card palette for the Apps page (webapp-home-style cards). Derived
// from each app's Tailwind color family so the icon box, its border, and the
// hover gradient all share a hue. Keyed by app id; falls back to a neutral
// slate when an id is missing.
// from each app's Tailwind color family so the icon tile, its border, and the
// hover state all share a hue. Keyed by app id; falls back to a neutral tone
// when an id is missing.
interface AppCardPalette {
/** Hover gradient overlay, e.g. "from-blue-500/20 to-blue-500/0". */
/** Hover tint for the card, e.g. "from-blue-500/20 to-blue-500/0". Legacy. */
accent: string;
/** Icon box background + border, e.g. "bg-blue-500/20 border-blue-400/30". */
/** Icon tile background + border, e.g. "bg-blue-500/20 border-blue-400/40". */
iconBg: string;
/** Icon glyph color, e.g. "text-blue-300". */
iconColor: string;
/** Card hover border + background, e.g. "hover:border-blue-400/60 hover:bg-blue-500/10". */
hoverStyle: string;
}
const APP_CARD_PALETTES: Record<string, AppCardPalette> = {
"text-to-image": {
accent: "from-blue-500/20 to-blue-500/0",
iconBg: "bg-blue-500/20 border-blue-400/30",
iconBg: "bg-blue-500/20 border-blue-400/40",
iconColor: "text-blue-300",
hoverStyle: "hover:border-blue-400/60 hover:bg-blue-500/10",
},
"image-to-video": {
accent: "from-amber-500/20 to-amber-500/0",
iconBg: "bg-amber-500/20 border-amber-400/30",
iconColor: "text-amber-300",
accent: "from-purple-500/20 to-purple-500/0",
iconBg: "bg-purple-500/20 border-purple-400/40",
iconColor: "text-purple-300",
hoverStyle: "hover:border-purple-400/60 hover:bg-purple-500/10",
},
"create-audio": {
accent: "from-pink-500/20 to-pink-500/0",
iconBg: "bg-pink-500/20 border-pink-400/30",
iconBg: "bg-pink-500/20 border-pink-400/40",
iconColor: "text-pink-300",
hoverStyle: "hover:border-pink-400/60 hover:bg-pink-500/10",
},
"image-to-3d-object": {
accent: "from-emerald-500/20 to-emerald-500/0",
iconBg: "bg-emerald-500/20 border-emerald-400/30",
iconColor: "text-emerald-300",
accent: "from-cyan-500/20 to-cyan-500/0",
iconBg: "bg-cyan-500/20 border-cyan-400/40",
iconColor: "text-cyan-300",
hoverStyle: "hover:border-cyan-400/60 hover:bg-cyan-500/10",
},
"image-to-3d-world": {
accent: "from-teal-500/20 to-teal-500/0",
iconBg: "bg-teal-500/20 border-teal-400/40",
iconColor: "text-teal-300",
hoverStyle: "hover:border-teal-400/60 hover:bg-teal-500/10",
},
"3d-editor": {
accent: "from-amber-500/20 to-amber-500/0",
iconBg: "bg-amber-500/20 border-amber-400/40",
iconColor: "text-amber-300",
hoverStyle: "hover:border-amber-400/60 hover:bg-amber-500/10",
},
"background-change": {
accent: "from-emerald-500/20 to-emerald-500/0",
iconBg: "bg-emerald-500/20 border-emerald-400/40",
iconColor: "text-emerald-300",
hoverStyle: "hover:border-emerald-400/60 hover:bg-emerald-500/10",
},
"video-editor": {
accent: "from-rose-500/20 to-rose-500/0",
iconBg: "bg-rose-500/20 border-rose-400/40",
iconColor: "text-rose-300",
hoverStyle: "hover:border-rose-400/60 hover:bg-rose-500/10",
},
moodboard: {
accent: "from-indigo-500/20 to-indigo-500/0",
iconBg: "bg-indigo-500/20 border-indigo-400/40",
iconColor: "text-indigo-300",
hoverStyle: "hover:border-indigo-400/60 hover:bg-indigo-500/10",
},
"video-frame-extractor": {
accent: "from-orange-500/20 to-orange-500/0",
iconBg: "bg-orange-500/20 border-orange-400/40",
iconColor: "text-orange-300",
hoverStyle: "hover:border-orange-400/60 hover:bg-orange-500/10",
},
"edit-image": {
accent: "from-sky-500/20 to-sky-500/0",
iconBg: "bg-sky-500/20 border-sky-400/30",
iconBg: "bg-sky-500/20 border-sky-400/40",
iconColor: "text-sky-300",
},
angles: {
accent: "from-lime-500/20 to-lime-500/0",
iconBg: "bg-lime-500/20 border-lime-400/30",
iconColor: "text-lime-300",
},
storyboard: {
accent: "from-fuchsia-500/20 to-fuchsia-500/0",
iconBg: "bg-fuchsia-500/20 border-fuchsia-400/30",
iconColor: "text-fuchsia-300",
hoverStyle: "hover:border-sky-400/60 hover:bg-sky-500/10",
},
"2d-canvas": {
accent: "from-sky-500/20 to-sky-500/0",
iconBg: "bg-sky-500/20 border-sky-400/30",
iconBg: "bg-sky-500/20 border-sky-400/40",
iconColor: "text-sky-300",
},
"3d-editor": {
accent: "from-emerald-500/20 to-emerald-500/0",
iconBg: "bg-emerald-500/20 border-emerald-400/30",
iconColor: "text-emerald-300",
},
"edit-image": {
accent: "from-purple-500/20 to-purple-500/0",
iconBg: "bg-purple-500/20 border-purple-400/30",
iconColor: "text-purple-300",
hoverStyle: "hover:border-sky-400/60 hover:bg-sky-500/10",
},
"remove-background": {
accent: "from-violet-500/20 to-violet-500/0",
iconBg: "bg-violet-500/20 border-violet-400/30",
iconBg: "bg-violet-500/20 border-violet-400/40",
iconColor: "text-violet-300",
hoverStyle: "hover:border-violet-400/60 hover:bg-violet-500/10",
},
"video-frame-extractor": {
accent: "from-rose-500/20 to-rose-500/0",
iconBg: "bg-rose-500/20 border-rose-400/30",
iconColor: "text-rose-300",
angles: {
accent: "from-lime-500/20 to-lime-500/0",
iconBg: "bg-lime-500/20 border-lime-400/40",
iconColor: "text-lime-300",
hoverStyle: "hover:border-lime-400/60 hover:bg-lime-500/10",
},
"background-change": {
accent: "from-orange-500/20 to-orange-500/0",
iconBg: "bg-orange-500/20 border-orange-400/30",
iconColor: "text-orange-300",
},
"video-editor": {
accent: "from-teal-500/20 to-teal-500/0",
iconBg: "bg-teal-500/20 border-teal-400/30",
iconColor: "text-teal-300",
storyboard: {
accent: "from-fuchsia-500/20 to-fuchsia-500/0",
iconBg: "bg-fuchsia-500/20 border-fuchsia-400/40",
iconColor: "text-fuchsia-300",
hoverStyle: "hover:border-fuchsia-400/60 hover:bg-fuchsia-500/10",
},
"video-watermark-removal": {
accent: "from-cyan-500/20 to-cyan-500/0",
iconBg: "bg-cyan-500/20 border-cyan-400/30",
iconColor: "text-cyan-300",
accent: "from-yellow-500/20 to-yellow-500/0",
iconBg: "bg-yellow-500/20 border-yellow-400/40",
iconColor: "text-yellow-300",
hoverStyle: "hover:border-yellow-400/60 hover:bg-yellow-500/10",
},
"image-watermark-removal": {
accent: "from-indigo-500/20 to-indigo-500/0",
iconBg: "bg-indigo-500/20 border-indigo-400/30",
iconColor: "text-indigo-300",
accent: "from-red-500/20 to-red-500/0",
iconBg: "bg-red-500/20 border-red-400/40",
iconColor: "text-red-300",
hoverStyle: "hover:border-red-400/60 hover:bg-red-500/10",
},
};
@ -182,6 +206,7 @@ const FALLBACK_APP_CARD_PALETTE: AppCardPalette = {
accent: "from-white/10 to-white/0",
iconBg: "bg-ui-controls border-ui-controls-border",
iconColor: "text-base-fg",
hoverStyle: "hover:border-white/30 hover:bg-white/10",
};
export const getAppCardPalette = (id: string): AppCardPalette =>
@ -387,13 +412,13 @@ export const useEditApps = (): FullAppItem[] => {
export const getBadgeStyles = (badge?: string) => {
switch (badge) {
case "NEW":
return "bg-teal-600 text-white";
return "border-purple-400/40 text-purple-300";
case "BEST":
return "bg-primary text-white";
return "border-primary/30 text-ui-accent-ink";
case "SOON":
return "bg-gray-600 text-white";
return "border-white/20 text-base-fg/50";
case "BETA":
return "bg-amber-500 text-white";
return "border-amber-400/40 text-amber-300";
default:
return "";
}

View File

@ -10,8 +10,7 @@
// siblings, never wrapped by EngineProvider, so they have no
// dependency on the 3D engine being present.
import { useEffect, useState } from "react";
import * as gpu from "detect-gpu";
import { lazy, Suspense, useEffect } from "react";
import { useSignals } from "@preact/signals-react/runtime";
import { TopBar } from "~/components";
@ -58,26 +57,55 @@ import { useTextToImageStore } from "./PageImage/TextToImageStore";
import { AppsIndexPage } from "./PageApps/AppsIndexPage";
import PageDraw from "./PageDraw/PageDraw";
import TextToImage from "./PageImage/TextToImage";
import ImageToVideo from "./PageVideo/ImageToVideo";
import CreateAudio from "./PageAudio/CreateAudio";
import { VideoFrameExtractor } from "./PageVideoFrameExtractor";
import { VideoWatermarkRemover } from "./PageVideoWatermarkRemover";
import { ImageWatermarkRemover } from "./PageImageWatermarkRemover";
import { ImageTo3DObject } from "./PageImageTo3DObject";
import { ImageTo3DWorld } from "./PageImageTo3DWorld";
import { RemoveBackground } from "./PageRemoveBackground";
import { Angles } from "./PageAngles";
import { Storyboard } from "./PageStoryboard";
import { PageBackgroundChange } from "./PageBackgroundChange";
import { PageScene } from "./PageScene";
import { PageVideoEditor } from "./PageVideoEditor";
import { PageMoodboard } from "./PageMoodboard";
import {
topNavMediaId,
topNavMediaUrl,
} from "~/components/signaled/TopBar/TopBar";
// Load editors when selected, keeping their code off the launch path. Drawing
// stays eager: its shared store/UI is already needed by the shell, so deferring
// its small host adapter adds first-open latency for very little byte saving.
// Declare lazy components once so navigating does not recreate their identity.
const TextToImage = lazy(() => import("./PageImage/TextToImage"));
const ImageToVideo = lazy(() => import("./PageVideo/ImageToVideo"));
const CreateAudio = lazy(() => import("./PageAudio/CreateAudio"));
const VideoFrameExtractor = lazy(() =>
import("./PageVideoFrameExtractor").then((m) => ({ default: m.VideoFrameExtractor })),
);
const VideoWatermarkRemover = lazy(() =>
import("./PageVideoWatermarkRemover").then((m) => ({ default: m.VideoWatermarkRemover })),
);
const ImageWatermarkRemover = lazy(() =>
import("./PageImageWatermarkRemover").then((m) => ({ default: m.ImageWatermarkRemover })),
);
const ImageTo3DObject = lazy(() =>
import("./PageImageTo3DObject").then((m) => ({ default: m.ImageTo3DObject })),
);
const ImageTo3DWorld = lazy(() =>
import("./PageImageTo3DWorld").then((m) => ({ default: m.ImageTo3DWorld })),
);
const RemoveBackground = lazy(() =>
import("./PageRemoveBackground").then((m) => ({ default: m.RemoveBackground })),
);
const Angles = lazy(() =>
import("./PageAngles").then((m) => ({ default: m.Angles })),
);
const Storyboard = lazy(() =>
import("./PageStoryboard").then((m) => ({ default: m.Storyboard })),
);
const PageBackgroundChange = lazy(() =>
import("./PageBackgroundChange").then((m) => ({ default: m.PageBackgroundChange })),
);
const PageScene = lazy(() =>
import("./PageScene").then((m) => ({ default: m.PageScene })),
);
const PageVideoEditor = lazy(() =>
import("./PageVideoEditor").then((m) => ({ default: m.PageVideoEditor })),
);
const PageMoodboard = lazy(() =>
import("./PageMoodboard").then((m) => ({ default: m.PageMoodboard })),
);
interface Props {
sceneToken?: string;
}
@ -121,8 +149,7 @@ export const MainApp = ({ sceneToken }: Props) => {
toast.error("File deleted.");
});
// Session probe (runs once per shell mount) and GPU detection.
// Both are app-wide concerns, not 3D-only.
// Session probe (runs once per shell mount).
useEffect(() => {
const usersApi = new UsersApi();
usersApi.GetSession().then((result) => {
@ -132,20 +159,6 @@ export const MainApp = ({ sceneToken }: Props) => {
});
}, []);
const [, setValidGpu] = useState("unknown");
useEffect(() => {
const { getGPUTier } = gpu;
getGPUTier().then((gpuTier) => {
console.log("GPU tier", gpuTier);
let isValid = false;
const fps = gpuTier.fps || 0;
if (gpuTier.tier > 1) isValid = true;
if (fps > 15) isValid = true;
if (gpuTier.gpu === "apple gpu (Apple GPU)") isValid = true;
setValidGpu(isValid ? "valid" : "error");
});
}, []);
const { triggerRecheck } = useLoginModalStore();
const { isOpen: isCreditsOpen, closeModal: closeCreditsModal } =
useCreditsModalStore();
@ -179,7 +192,18 @@ export const MainApp = ({ sceneToken }: Props) => {
}}
/>
<TabBody sceneToken={sceneToken} />
<Suspense
fallback={
<div
role="status"
className="flex h-[calc(100vh-56px)] items-center justify-center text-base-fg/60"
>
Loading…
</div>
}
>
<TabBody sceneToken={sceneToken} />
</Suspense>
<GalleryDragComponent />
<ErrorDialog />
@ -210,7 +234,7 @@ export const MainApp = ({ sceneToken }: Props) => {
};
const TabBody = ({ sceneToken }: { sceneToken?: string }) => {
const tabStore = useTabStore();
const activeTabId = useTabStore((s) => s.activeTabId);
const storyboardPageEnabled = useStoryboardPageEnabled();
// The 3D case stays unwrapped because Stage3DBody (lib) already
@ -218,7 +242,7 @@ const TabBody = ({ sceneToken }: { sceneToken?: string }) => {
// top-level children may use position: fixed (e.g. PageDraw); the
// wrapping <div> scopes them so they don't stack as siblings of
// the TopBar at the MainApp root.
switch (tabStore.activeTabId) {
switch (activeTabId) {
case "3D":
return <PageScene sceneToken={sceneToken} />;
case "APPS":

View File

@ -482,7 +482,7 @@ export const Angles = () => {
/* ──── Upload screen ──── */
<div className="flex flex-1 items-center justify-center p-8 lg:p-16">
<div className="w-full max-w-5xl">
<div className="relative aspect-video overflow-hidden rounded-2xl border border-ui-panel-border bg-ui-panel shadow-lg">
<div className="relative aspect-video overflow-hidden border border-ui-panel-border bg-ui-panel">
<UploadEntryCard
icon={CrosshairIcon}
title="Angles"
@ -498,7 +498,7 @@ export const Angles = () => {
disabled={isLoadingImage}
/>
{isLoadingImage && (
<div className="bg-ui-panel/80 absolute inset-0 flex items-center justify-center backdrop-blur-sm">
<div className="bg-ui-panel/80 absolute inset-0 flex items-center justify-center">
<LoadingSpinner className="h-12 w-12" />
</div>
)}
@ -519,7 +519,7 @@ export const Angles = () => {
{/* Full-bleed image display */}
<div className="flex h-full w-full items-center justify-center px-16 pb-56 pt-16">
<div
className="relative overflow-hidden rounded-xl shadow-lg"
className="relative overflow-hidden"
style={imageContainerStyle}
>
{activeAngle ? (
@ -584,12 +584,12 @@ export const Angles = () => {
{/* ── Floating bottom angle controls ── */}
<div className="absolute bottom-4 left-1/2 z-10 w-[calc(100%-32px)] max-w-[860px] -translate-x-1/2">
<div className="glass flex items-center gap-4 rounded-xl px-4 lg:gap-5 lg:px-5">
<div className="glass flex items-center gap-4 rounded-none px-4 lg:gap-5 lg:px-5">
{/* Orbit sphere */}
<div className="relative shrink-0 px-5 py-5">
<button
onClick={() => handleTiltStep(1)}
className="absolute left-1/2 top-0 z-10 -translate-x-1/2 p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
className="absolute left-1/2 top-0 z-10 -translate-x-1/2 rounded-[3px] p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
>
<ChevronUpIcon
@ -597,7 +597,7 @@ export const Angles = () => {
</button>
<button
onClick={() => handleTiltStep(-1)}
className="absolute bottom-0 left-1/2 z-10 -translate-x-1/2 p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
className="absolute bottom-0 left-1/2 z-10 -translate-x-1/2 rounded-[3px] p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
>
<ChevronDownIcon
@ -605,7 +605,7 @@ export const Angles = () => {
</button>
<button
onClick={() => handleRotationStep(-1)}
className="absolute left-0 top-1/2 z-10 -translate-y-1/2 p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
className="absolute left-0 top-1/2 z-10 -translate-y-1/2 rounded-[3px] p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
>
<ChevronLeftIcon
@ -613,7 +613,7 @@ export const Angles = () => {
</button>
<button
onClick={() => handleRotationStep(1)}
className="absolute right-0 top-1/2 z-10 -translate-y-1/2 p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
className="absolute right-0 top-1/2 z-10 -translate-y-1/2 rounded-[3px] p-1 text-base-fg/40 transition-colors hover:text-base-fg/80"
>
<ChevronRightIcon
@ -633,7 +633,7 @@ export const Angles = () => {
{/* Sliders group */}
<div className="flex min-w-0 flex-1 flex-col gap-2">
<div className="flex items-center gap-3">
<span className="w-14 shrink-0 text-xs font-medium text-base-fg">
<span className="w-16 shrink-0 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
Rotation
</span>
<div className="min-w-0 flex-1">
@ -646,13 +646,13 @@ export const Angles = () => {
suffix="°"
/>
</div>
<span className="w-10 shrink-0 text-left text-xs tabular-nums text-base-fg/70">
<span className="w-10 shrink-0 text-left font-mono text-xs tabular-nums text-base-fg/70">
{rotationToDisplay(angleConfig.rotation)}°
</span>
</div>
<div className="flex items-center gap-3">
<span className="w-14 shrink-0 text-xs font-medium text-base-fg">
<span className="w-16 shrink-0 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
Tilt
</span>
<div className="min-w-0 flex-1">
@ -665,13 +665,13 @@ export const Angles = () => {
suffix="°"
/>
</div>
<span className="w-9 shrink-0 text-left text-xs tabular-nums text-base-fg/70">
<span className="w-9 shrink-0 text-left font-mono text-xs tabular-nums text-base-fg/70">
{angleConfig.tilt}°
</span>
</div>
<div className="flex items-center gap-3">
<span className="w-14 shrink-0 text-xs font-medium text-base-fg">
<span className="w-16 shrink-0 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
Zoom
</span>
<div className="min-w-0 flex-1">
@ -683,7 +683,7 @@ export const Angles = () => {
onChange={handleZoomSlider}
/>
</div>
<span className="w-9 shrink-0 text-left text-xs tabular-nums text-base-fg/70">
<span className="w-9 shrink-0 text-left font-mono text-xs tabular-nums text-base-fg/70">
{angleConfig.zoom}
</span>
</div>

View File

@ -23,28 +23,35 @@ export const AppsIndexPage = () => {
// flush against the right edge; horizontal padding lives on the inner
// wrapper instead.
<div className="fixed inset-0 overflow-y-auto bg-ui-background pt-[56px] text-base-fg">
<main className="mx-auto max-w-6xl px-6 pb-20 pt-12 sm:pt-20">
<h1 className="mx-auto text-center text-4xl font-semibold tracking-tight sm:text-6xl">
What will you <span className="text-primary">craft</span> today?
<main className="mx-auto w-full max-w-6xl px-5 pb-20 pt-8 sm:px-8 sm:pt-12">
<p className="hud-label mb-4 text-ui-accent-ink">
Your creative workspace
</p>
<h1 className="max-w-3xl font-display text-3xl leading-tight tracking-tight sm:text-5xl">
What will you <span className="text-ui-accent-ink">craft</span> today?
</h1>
<p className="mx-auto mt-3 max-w-xl text-center text-lg text-base-fg/55">
Every tool in your toolbox - pick one and start creating.
<p className="mt-4 max-w-xl text-sm leading-relaxed text-base-fg/70 sm:text-base">
Start with an idea. Choose a tool to bring it to life.
</p>
<div className="mt-12 space-y-10">
{categories.map((category) => (
<section key={category.title}>
<h2 className="mb-4 text-sm font-semibold text-base-fg/85">
{category.title}
</h2>
<div className="grid auto-rows-min gap-3 sm:grid-cols-2 lg:grid-cols-3">
{category.apps.map((app) => (
<AppCard key={app.id} app={app} />
))}
</div>
</section>
))}
</div>
{categories.map((category, index) => (
<section
key={category.title}
className={twMerge(
"border-t border-ui-border pt-6",
index === 0 ? "mt-8 sm:mt-10" : "mt-10",
)}
>
<h2 className="hud-label mb-4 text-base-fg/70">
{category.title}
</h2>
<div className="grid auto-rows-fr gap-3 md:grid-cols-2 xl:grid-cols-3">
{category.apps.map((app) => (
<AppCard key={app.id} app={app} />
))}
</div>
</section>
))}
</main>
</div>
);
@ -59,27 +66,14 @@ function AppCard({ app }: { app: FullAppItem }) {
onClick={() => goToApp(app.action)}
disabled={!enabled}
className={twMerge(
"group relative block overflow-hidden rounded-2xl bg-ui-controls/50 p-5 text-left transition-colors",
enabled
? "cursor-pointer hover:bg-ui-controls"
: "cursor-default opacity-60",
"group relative flex h-full rounded-[3px] border border-ui-border bg-white/5 p-5 text-left transition-colors duration-150 focus-visible:border-primary",
enabled ? twMerge("cursor-pointer", palette.hoverStyle) : "cursor-default opacity-60",
)}
>
{/* Hover accent — gradient wash matching the app's hue. */}
{enabled && (
<div
aria-hidden
className={twMerge(
"pointer-events-none absolute -inset-px rounded-2xl bg-gradient-to-br opacity-0 transition-opacity group-hover:opacity-100",
palette.accent,
)}
/>
)}
<div className="relative flex items-start gap-4">
<div className="relative flex w-full items-start gap-4">
<div
className={twMerge(
"flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border",
"flex h-10 w-10 shrink-0 items-center justify-center border",
palette.iconBg,
palette.iconColor,
)}
@ -88,15 +82,17 @@ function AppCard({ app }: { app: FullAppItem }) {
</div>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<h3 className="truncate text-base font-semibold text-base-fg">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<h3 className="text-base font-bold uppercase tracking-tight text-ui-ink">
{app.label}
</h3>
{app.badge && (
<span
className={twMerge(
"shrink-0 rounded-full px-1.5 py-0.5 text-[10px] font-bold uppercase leading-none tracking-wider",
getBadgeStyles(app.badge),
"shrink-0 border px-1.5 py-1 font-mono text-[9px] font-medium leading-none tracking-wider",
app.badge === "SOON"
? getBadgeStyles(app.badge)
: "border-primary/30 text-ui-accent-ink",
)}
>
{app.badge}
@ -104,12 +100,12 @@ function AppCard({ app }: { app: FullAppItem }) {
)}
</div>
{enabled && (
<ArrowRightIcon
className="text-sm text-base-fg/40 transition-all group-hover:translate-x-0.5 group-hover:text-base-fg/70" />
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-[3px] border border-white/15 text-white/40 transition-colors duration-150 group-hover:border-white/40 group-hover:text-white">
<ArrowRightIcon className="text-xs" />
</span>
)}
</div>
<p className="mt-1 text-sm leading-snug text-base-fg/55">
<p className="mt-2 text-sm leading-relaxed text-base-fg/70">
{app.description}
</p>
</div>

View File

@ -8,7 +8,6 @@ import {
FilterMediaClasses,
} from "@storyteller/api";
import { useOmniGenAudioModels, useAudioCostEstimate } from "@storyteller/omni-gen";
import BackgroundGallery from "../PageImage/BackgroundGallery";
import {
galleryModalLightboxImage,
galleryModalLightboxMediaId,
@ -149,7 +148,6 @@ const CreateAudio = () => {
hasContent={hasContent}
emptyStateTitle="Create Audio"
emptyStateSubtitle="Describe a song, a sound, or a sample"
background={<BackgroundGallery />}
bottomOffset={promptHeight + 40}
listContent={
<DesktopGenerationGallery

View File

@ -1,11 +1,9 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { SparklesIcon } from "lucide-react";
import { toast } from "@storyteller/ui-toaster";
import { UploadImageMedia, UploadVideoMedia } from "@storyteller/api";
import {
PromptBoxVFX,
SubTabStrip,
TruchetPattern,
VFXResultCard,
VFXShowcaseView,
newIdempotencyToken,
@ -14,6 +12,7 @@ import {
VFX_NOT_AVAILABLE_ERROR,
VFX_SHOWCASE,
} from "@storyteller/ui-vfx";
import { CreateEmptyState } from "~/components/generation-feed/CreateEmptyState";
export const PageBackgroundChange = () => {
const subTab = useVFXStore((s) => s.subTab);
@ -113,34 +112,17 @@ export const PageBackgroundChange = () => {
className="relative flex flex-1 items-center justify-center px-6"
style={{ paddingBottom: Math.max(promptBoxHeight + 36, 240) }}
>
<div
aria-hidden
className="pointer-events-none absolute inset-0 z-0"
style={{
maskImage:
"radial-gradient(ellipse 60% 60% at 50% 45%, black 30%, transparent 85%)",
WebkitMaskImage:
"radial-gradient(ellipse 60% 60% at 50% 45%, black 30%, transparent 85%)",
}}
>
<TruchetPattern
intensity={0.8}
className="absolute inset-0 h-full w-full"
/>
</div>
<div className="relative z-10">
<EmptyState
title="No background changes yet"
subtitle="Upload a source video and a reference image, then optionally add a prompt."
/>
</div>
<CreateEmptyState
title="No background changes yet"
subtitle="Upload a source video and a reference image, then optionally add a prompt."
/>
</div>
) : (
<div
className="flex-1 overflow-y-auto"
style={{ paddingBottom: Math.max(promptBoxHeight + 36, 240) }}
>
<div className="flex flex-col gap-10 px-6 pt-6">
<div className="flex flex-col items-center gap-10 px-6 pt-6">
{history.map((r) => (
<VFXResultCard
key={r.id}
@ -155,6 +137,7 @@ export const PageBackgroundChange = () => {
failureReason: r.failureReason,
}}
onDismiss={() => dismissResult(r.id)}
className="w-[min(960px,calc(100vw-32px))]"
/>
))}
</div>
@ -163,7 +146,7 @@ export const PageBackgroundChange = () => {
<div
aria-hidden
className="via-ui-background/85 pointer-events-none fixed bottom-0 left-0 right-0 z-20 h-72 bg-gradient-to-t from-ui-background to-transparent"
className="pointer-events-none fixed bottom-0 left-0 right-0 z-20 h-72 bg-gradient-to-t from-ui-background via-ui-background/85 to-transparent"
/>
<div
@ -184,19 +167,4 @@ export const PageBackgroundChange = () => {
);
};
interface EmptyStateProps {
title: string;
subtitle: string;
}
const EmptyState = ({ title, subtitle }: EmptyStateProps) => (
<div className="flex max-w-md flex-col items-center gap-4 text-center">
<div className="flex h-16 w-16 items-center justify-center rounded-2xl bg-base-fg/5 ring-1 ring-base-fg/10">
<SparklesIcon className="text-2xl" />
</div>
<h3 className="text-2xl font-bold text-base-fg">{title}</h3>
<p className="max-w-xs text-sm text-base-fg/60">{subtitle}</p>
</div>
);
export default PageBackgroundChange;

View File

@ -1,17 +0,0 @@
.stretch-background-image {
background-image:
linear-gradient(
0deg,
rgb(var(--st-photo-tint-rgb) / var(--st-photo-tint-alpha)),
rgb(var(--st-photo-tint-rgb) / var(--st-photo-tint-alpha))
),
url("/resources/images/digital-mountains.webp");
background-repeat: no-repeat;
background-size: cover;
position: fixed;
right: 0;
bottom: 0;
min-width: 100%;
min-height: 100%;
filter: grayscale(var(--st-photo-grayscale));
}

View File

@ -1,16 +0,0 @@
import "./Background.css";
export default function GalleryBackground() {
return (
<>
<div className="pointer-events-none fixed inset-0 z-[1] overflow-hidden bg-[radial-gradient(50%_50%_at_50%_50%,_transparent_49%,_rgb(var(--st-controls-rgb)_/_var(--st-gallery-vignette-alpha))_100%)]" />
<div className="fixed inset-0 z-0 overflow-hidden">
<div
className={`stretch-background-image h-full w-full opacity-30 transition-opacity duration-1000`}
>
<div className="absolute inset-0 grid grid-cols-5 gap-6 px-6 opacity-35" />
</div>
</div>
</>
);
}

View File

@ -2,7 +2,6 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { JobContextType } from "@storyteller/common";
import { PromptBoxImage } from "@storyteller/ui-promptbox";
import { UploadImageMedia, FilterMediaClasses } from "@storyteller/api";
import BackgroundGallery from "./BackgroundGallery";
import {
useTextToImagePageModelList,
ModelPage,
@ -158,7 +157,6 @@ const TextToImage = ({ imageMediaId, imageUrl }: TextToImageProps) => {
hasContent={hasContent}
emptyStateTitle="Create Image"
emptyStateSubtitle="Add a prompt, then generate"
background={<BackgroundGallery />}
bottomOffset={promptHeight + 40}
listContent={
<DesktopGenerationGallery

View File

@ -6,7 +6,6 @@ export const ImageTo3DObject = () => {
title="Generate 3D Object"
subtitle="Transform your image into a 3D object with textures."
variant="object"
backgroundImage="/resources/images/floating-cubes.webp"
/>
);
};

View File

@ -6,7 +6,6 @@ export const ImageTo3DWorld = () => {
title="Image to 3D World"
subtitle="Generate 3D worlds from an image with World Labs"
variant="world"
backgroundImage="/resources/images/room-of-items.webp"
/>
);
};

View File

@ -104,7 +104,7 @@ export const ImageWatermarkRemover = () => {
return (
<>
<div className="bg-ui-panel-gradient flex h-[calc(100vh-56px)] w-full overflow-hidden bg-ui-panel text-base-fg">
<div className="flex h-[calc(100vh-56px)] w-full overflow-hidden bg-ui-background text-base-fg">
<div className="flex-1 overflow-y-auto">
<main
className={
@ -115,7 +115,7 @@ export const ImageWatermarkRemover = () => {
>
{!imageUrl ? (
<div className="w-full max-w-5xl">
<div className="aspect-video overflow-hidden rounded-2xl border border-ui-panel-border bg-ui-background shadow-lg">
<div className="aspect-video overflow-hidden border border-ui-panel-border bg-ui-panel">
<UploadEntryCard
icon={DropletIcon}
title="Remove Image Watermark"
@ -133,7 +133,7 @@ export const ImageWatermarkRemover = () => {
</div>
) : (
<div className="flex w-full max-w-5xl flex-col gap-5">
<div className="w-full overflow-hidden rounded-2xl border border-ui-panel-border bg-ui-background shadow-lg">
<div className="w-full overflow-hidden border border-ui-panel-border bg-ui-panel">
<div className="relative w-full bg-black">
<Button
icon={RotateCwIcon}
@ -142,7 +142,7 @@ export const ImageWatermarkRemover = () => {
setImageUrl("");
setImageDimensions(null);
}}
className="absolute right-3 top-3 z-10 border-2 border-red/50 px-3 py-1.5 text-sm hover:border-red/80 hover:bg-red/80"
className="absolute right-3 top-3 z-10 border border-red/50 px-3 py-1.5 text-sm hover:border-red/80 hover:bg-red/80"
>
Switch Image
</Button>
@ -151,7 +151,7 @@ export const ImageWatermarkRemover = () => {
ref={imageRef}
src={imageUrl}
alt="Selected pic"
className="max-h-[70vh] max-w-full rounded-lg object-contain shadow-2xl"
className="max-h-[70vh] max-w-full object-contain"
onLoad={(e) => {
const img = e.currentTarget;
setImageDimensions({
@ -177,12 +177,12 @@ export const ImageWatermarkRemover = () => {
</Button>
</div>
<div className="rounded-2xl border border-ui-panel-border bg-ui-background p-6 shadow-lg">
<div className="border border-ui-panel-border bg-ui-panel p-6">
<div>
<div className="mb-4 flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-base-fg/60">
<div className="mb-4 flex items-center gap-2 font-mono text-[11px] font-semibold uppercase tracking-[0.12em] text-base-fg/60">
<ImagesIcon
className="text-primary" />
className="text-ui-accent-ink" />
Image Information
</div>
{imageDimensions ? (
@ -191,7 +191,7 @@ export const ImageWatermarkRemover = () => {
<span className="font-medium text-base-fg/70">
Resolution
</span>
<span className="font-mono text-lg font-bold text-base-fg">
<span className="font-mono text-lg font-semibold tabular-nums text-base-fg">
{imageDimensions.width} × {imageDimensions.height}
</span>
</div>
@ -199,7 +199,7 @@ export const ImageWatermarkRemover = () => {
<span className="font-medium text-base-fg/70">
Aspect Ratio
</span>
<span className="font-mono text-lg font-bold text-base-fg">
<span className="font-mono text-lg font-semibold tabular-nums text-base-fg">
{(
imageDimensions.width / imageDimensions.height
).toFixed(2)}

View File

@ -543,12 +543,12 @@ export const RemoveBackground = () => {
return (
<>
<div className="bg-ui-panel-gradient flex h-[calc(100vh-56px)] w-full overflow-hidden bg-ui-panel text-base-fg">
<div className="flex h-[calc(100vh-56px)] w-full overflow-hidden bg-ui-panel text-base-fg">
<div className="flex flex-1 items-center justify-center overflow-y-auto p-16">
<main className="flex h-full w-full flex-col items-center justify-center">
{showUploadScreen ? (
<div className="w-full max-w-5xl">
<div className="relative aspect-video overflow-hidden rounded-2xl border border-ui-panel-border bg-ui-background shadow-lg">
<div className="relative aspect-video overflow-hidden border border-ui-panel-border bg-ui-background">
<UploadEntryCard
icon={WandSparklesIcon}
title="Remove Background"
@ -564,7 +564,7 @@ export const RemoveBackground = () => {
disabled={isLoadingImage}
/>
{isLoadingImage && (
<div className="bg-ui-panel/80 absolute inset-0 flex items-center justify-center backdrop-blur-sm">
<div className="bg-ui-panel/80 absolute inset-0 flex items-center justify-center">
<LoadingSpinner className="h-12 w-12" />
</div>
)}
@ -580,9 +580,9 @@ export const RemoveBackground = () => {
onMouseDown={handleCompareMouseDown}
disabled={!activeImage || isProcessing}
className={twMerge(
"border-ui-controls-border select-none border-2 px-6 py-2.5 text-sm font-semibold transition-all",
"border-ui-controls-border select-none border px-6 py-2.5 text-sm font-semibold transition-all",
isHoldingCompare
? "border-primary bg-primary/20"
? "border-white bg-white/10"
: "border-ui-controls-border",
(!activeImage || isProcessing) &&
"cursor-not-allowed opacity-50",
@ -598,7 +598,7 @@ export const RemoveBackground = () => {
onClick={handleDownload}
disabled={!activeImage || isProcessing}
className={twMerge(
"select-none border-2 border-primary px-6 py-2.5 text-sm font-semibold transition-all",
"select-none px-6 py-2.5 text-sm font-semibold transition-all",
(!activeImage || isProcessing) &&
"cursor-not-allowed opacity-50",
)}
@ -610,11 +610,11 @@ export const RemoveBackground = () => {
<div className="flex flex-1 items-center justify-center">
<div
className="relative overflow-hidden rounded-2xl border border-ui-panel-border shadow-xl"
className="relative overflow-hidden border border-ui-panel-border"
style={imageContainerStyle}
>
{isProcessing && (
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-black/60 backdrop-blur-sm">
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-black/70">
{currentOriginalUrl && (
<img
src={currentOriginalUrl}
@ -624,12 +624,12 @@ export const RemoveBackground = () => {
)}
<div className="relative z-10 flex flex-col items-center gap-4">
<div className="relative">
<div className="h-16 w-16 animate-spin rounded-full border-4 border-primary-500/30 border-t-primary-500" />
<div className="h-16 w-16 animate-spin rounded-full border-2 border-white/20 border-t-white" />
<WandSparklesIcon
className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-2xl text-primary-400" />
className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-2xl text-white" />
</div>
<span className="text-lg font-semibold text-white">
<span className="font-mono text-sm font-semibold uppercase tracking-[0.12em] text-white">
Removing Background...
</span>
</div>
@ -679,7 +679,7 @@ export const RemoveBackground = () => {
<div
ref={progressBarRef}
className="absolute bottom-0 top-0 w-1 bg-primary-500 shadow-lg shadow-primary-500/50"
className="absolute bottom-0 top-0 w-1 bg-white"
style={{
left: `${revealProgressRef.current}%`,
transform: "translateX(-50%)",
@ -695,7 +695,7 @@ export const RemoveBackground = () => {
</div>
</div>
<div className="mt-auto flex shrink-0 items-center gap-3 rounded-xl border border-ui-panel-border bg-ui-background p-2">
<div className="mt-auto flex shrink-0 items-center gap-3 border border-ui-panel-border bg-ui-background p-2">
<input
type="file"
ref={fileInputRef}
@ -711,7 +711,7 @@ export const RemoveBackground = () => {
position="top"
showIconsInList
buttonClassName={twMerge(
"h-14 w-14 border-2 border-dashed border-ui-panel-border bg-ui-controls/50",
"h-14 w-14 rounded-[3px] border border-dashed border-white/20 bg-white/[0.015] hover:border-white/40 hover:bg-white/5",
isProcessing && "cursor-not-allowed opacity-50",
)}
triggerIcon={
@ -724,10 +724,10 @@ export const RemoveBackground = () => {
key={img.id}
onClick={() => handleThumbnailClick(img)}
className={twMerge(
"relative h-14 w-14 overflow-hidden rounded-lg border-2 transition-all",
"relative h-14 w-14 overflow-hidden rounded-[3px] border transition-all",
img.id === activeImageId
? "border-primary ring-2 ring-primary/30"
: "border-transparent hover:border-primary/50",
? "border-white"
: "border-white/15 hover:border-white/30",
)}
>
<img

Some files were not shown because too many files have changed in this diff Show More