Compare commits

...
115 changed files with 3543 additions and 229 deletions
@@ -0,0 +1,194 @@
name: ArtCraft Linux release
on:
push:
branches: [release, artcraft-release, artcraft-linux]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: linux-release-${{ github.ref }}
cancel-in-progress: false
jobs:
packaging-check:
runs-on: ubuntu-22.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: storytold/craft-common-actions/actions/install-apt-packages@main
with:
packages: rpm jq binutils zsync
- run: packaging/linux/package-test.sh
build:
strategy:
fail-fast: false
matrix:
include:
- {arch: x86_64, runner: ubuntu-22.04, target: x86_64-unknown-linux-gnu, bundles: "deb,rpm,appimage"}
- {arch: aarch64, runner: ubuntu-22.04-arm, target: aarch64-unknown-linux-gnu, bundles: "deb,rpm,appimage"}
- {arch: riscv64, runner: ubuntu-24.04, target: riscv64gc-unknown-linux-gnu, bundles: "deb,rpm"}
runs-on: ${{ matrix.runner }}
timeout-minutes: 90
env:
SQLX_OFFLINE: 'true'
VITE_ENVIRONMENT_TYPE: production
TAURI_FRONTEND_PATH: ${{ github.workspace }}/frontend
TAURI_APP_PATH: ${{ github.workspace }}/crates/desktop/artcraft
steps:
- uses: actions/checkout@v4
- uses: storytold/craft-common-actions/actions/install-apt-packages@main
with:
packages: libwebkit2gtk-4.1-dev libappindicator3-dev librsvg2-dev patchelf libssl-dev libclang-dev libasound2-dev libxdo-dev libdbus-1-dev build-essential clang file jq perl cmake nasm rpm zsync gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-libav
- uses: storytold/craft-common-actions/actions/install-riscv64-cross@main
if: matrix.arch == 'riscv64'
- name: Remove conflicting host Pango development files
if: matrix.arch == 'riscv64'
# Ubuntu's Pango GIR differs by architecture despite being in a shared path.
# Only the target GTK development packages are needed for this cross build.
run: sudo apt-get remove -y libpango1.0-dev:amd64
- name: Install RISC-V WebKitGTK dependencies
if: matrix.arch == 'riscv64'
uses: storytold/craft-common-actions/actions/install-apt-packages@main
with:
packages: libwebkit2gtk-4.1-dev:riscv64 libappindicator3-dev:riscv64 libssl-dev:riscv64 libxdo-dev:riscv64 libdbus-1-dev:riscv64 g++-riscv64-linux-gnu
- name: Configure RISC-V cross compilation
if: matrix.arch == 'riscv64'
run: |
cat >> "$GITHUB_ENV" <<'ENV'
CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER=riscv64-linux-gnu-gcc
CC_riscv64gc_unknown_linux_gnu=riscv64-linux-gnu-gcc
CXX_riscv64gc_unknown_linux_gnu=riscv64-linux-gnu-g++
AR_riscv64gc_unknown_linux_gnu=riscv64-linux-gnu-ar
PKG_CONFIG_ALLOW_CROSS=1
PKG_CONFIG_PATH_riscv64gc_unknown_linux_gnu=/usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig
PKG_CONFIG_LIBDIR_riscv64gc_unknown_linux_gnu=/usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig
ENV
echo "CMAKE_TOOLCHAIN_FILE_riscv64gc_unknown_linux_gnu=$GITHUB_WORKSPACE/packaging/linux/riscv64.cmake" >> "$GITHUB_ENV"
- uses: actions/setup-node@v4
with:
node-version: '22'
cache: npm
cache-dependency-path: frontend/package-lock.json
- uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # v1
with:
toolchain: stable
targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3
with:
key: tauri-linux-${{ matrix.arch }}
cache-on-failure: true
- run: npm ci --ignore-scripts
working-directory: frontend
- run: ./node_modules/.bin/nx run artcraft:build
working-directory: frontend
- uses: tauri-apps/tauri-action@fce9c6108b31ea247710505d3aaaa893ee6768d4 # v0
with:
projectPath: crates/desktop/artcraft
args: --target ${{ matrix.target }} --bundles ${{ matrix.bundles }} --config ${{ github.workspace }}/packaging/linux/tauri.conf.json
- name: Package and verify Linux outputs
env:
ARCH: ${{ matrix.arch }}
TARGET: ${{ matrix.target }}
run: packaging/linux/package.sh "$ARCH" "$TARGET"
- uses: actions/upload-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
arch:
if: always() && !cancelled()
needs: build
runs-on: ubuntu-24.04
strategy:
matrix:
arch: [x86_64, aarch64]
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Find tarball
id: tarball
env:
ARCH: ${{ matrix.arch }}
run: |
shopt -s nullglob
files=(dist/linux/artcraft-*-linux-"$ARCH".tar.gz)
test "${#files[@]}" -eq 1
echo "path=${files[0]}" >> "$GITHUB_OUTPUT"
- uses: storytold/craft-common-actions/actions/arch-package@9d6790582b4997aa2120f4413cdb55c0b6f77fae # extra-depends support (#161)
with:
tarball: ${{ steps.tarball.outputs.path }}
arch: ${{ matrix.arch }}
extra-depends: webkit2gtk-4.1 gtk3 openssl
- name: Verify Arch runtime dependencies
run: |
for package in dist/release/*.pkg.tar.zst; do
tar --zstd -xOf "$package" .PKGINFO | grep -Fx 'depend = webkit2gtk-4.1'
done
- uses: actions/upload-artifact@v4
with:
name: release-arch-${{ matrix.arch }}
path: dist/release/*.pkg.tar.zst
if-no-files-found: error
flatpak:
if: always() && !cancelled()
needs: build
runs-on: ${{ matrix.runner }}
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
include:
- {arch: x86_64, runner: ubuntu-24.04}
- {arch: aarch64, runner: ubuntu-24.04-arm}
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- uses: storytold/craft-common-actions/actions/install-apt-packages@main
with:
packages: flatpak flatpak-builder elfutils librsvg2-common skopeo
- name: Allow Flatpak build sandboxes
run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- uses: storytold/craft-common-actions/actions/import-signing-key@main
with:
key: ${{ secrets.LINUX_SIGNING_KEY }}
- name: Build Flatpak and publish OCI
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: packaging/linux/flatpak.sh
- uses: actions/upload-artifact@v4
with:
name: release-flatpak-${{ matrix.arch }}
path: |
dist/release/*.flatpak
dist/release/*.oci-manifest.json
if-no-files-found: error
release:
needs: [packaging-check, build, arch, flatpak]
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- name: Read version
id: version
run: echo "value=$(jq -r .version crates/desktop/artcraft/tauri.conf.json)" >> "$GITHUB_OUTPUT"
- name: Require signing key
env:
SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
run: test -n "$SIGNING_KEY"
- uses: storytold/craft-common-actions/actions/draft-release@main
with:
version: ${{ steps.version.outputs.value }}
app-title: ArtCraft
tag-prefix: artcraft-v
retain: "true"
allow-published: "true"
github-token: ${{ secrets.GITHUB_TOKEN }}
signing-key: ${{ secrets.LINUX_SIGNING_KEY }}
+10 -8
View File
@@ -84,7 +84,7 @@ jobs:
echo "Starting certificate import process..."
# Create certificate file
echo $APPLE_CERTIFICATE | base64 --decode > certificate.p12
echo "$APPLE_CERTIFICATE" | base64 --decode > certificate.p12
# Debug: Check if certificate file exists and has content
echo "Certificate file info:"
@@ -93,25 +93,25 @@ jobs:
# Debug: Check certificate contents without password (just structure)
echo "Certificate structure (may show error if password protected):"
openssl pkcs12 -info -in certificate.p12 -passin pass:$APPLE_CERTIFICATE_PASSWORD -noout || echo "Could not read certificate structure"
openssl pkcs12 -info -in certificate.p12 -passin pass:"$APPLE_CERTIFICATE_PASSWORD" -noout || echo "Could not read certificate structure"
# Debug: Try to list what's in the p12 file
echo "Attempting to list certificate contents:"
security cms -D -i certificate.p12 || echo "Not a CMS file, trying PKCS12..."
openssl pkcs12 -in certificate.p12 -passin pass:$APPLE_CERTIFICATE_PASSWORD -info -nodes 2>&1 | head -20 || echo "Failed to read PKCS12 contents"
openssl pkcs12 -in certificate.p12 -passin pass:"$APPLE_CERTIFICATE_PASSWORD" -info -nodes 2>&1 | head -20 || echo "Failed to read PKCS12 contents"
# Debug: Extract certificate details to verify type and expiration
echo "Extracting certificate details..."
# Extract just the certificate portion and examine it
openssl pkcs12 -in certificate.p12 -passin pass:$APPLE_CERTIFICATE_PASSWORD -nokeys 2>/dev/null | openssl x509 -text -noout | grep -E "(Subject:|Issuer:|Not Before|Not After)" || echo "Failed to parse certificate details"
openssl pkcs12 -in certificate.p12 -passin pass:"$APPLE_CERTIFICATE_PASSWORD" -nokeys 2>/dev/null | openssl x509 -text -noout | grep -E "(Subject:|Issuer:|Not Before|Not After)" || echo "Failed to parse certificate details"
# Also try to see what type of certificate this is
echo "Certificate type check:"
openssl pkcs12 -in certificate.p12 -passin pass:$APPLE_CERTIFICATE_PASSWORD -nokeys 2>/dev/null | openssl x509 -text -noout | grep -E "(CN=|OU=)" || echo "Could not determine certificate type"
openssl pkcs12 -in certificate.p12 -passin pass:"$APPLE_CERTIFICATE_PASSWORD" -nokeys 2>/dev/null | openssl x509 -text -noout | grep -E "(CN=|OU=)" || echo "Could not determine certificate type"
# Debug: Check if private key exists
echo "Checking for private key..."
openssl pkcs12 -in certificate.p12 -passin pass:$APPLE_CERTIFICATE_PASSWORD -nocerts -nodes 2>&1 | grep -E "(PRIVATE KEY|RSA KEY)" | head -5 || echo "No private key found"
openssl pkcs12 -in certificate.p12 -passin pass:"$APPLE_CERTIFICATE_PASSWORD" -nocerts -nodes 2>&1 | grep -E "(PRIVATE KEY|RSA KEY)" | head -5 || echo "No private key found"
# Create temporary keychain
security create-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
@@ -139,6 +139,7 @@ jobs:
security unlock-keychain -p "$KEYCHAIN_PASSWORD" build.keychain
# Add the keychain to the search list
# shellcheck disable=SC2046
security list-keychains -d user -s build.keychain $(security list-keychains -d user | sed 's/^[[:space:]]*"//;s/"$//')
# List all certificates to debug
@@ -181,11 +182,11 @@ jobs:
security find-certificate -c "Learning Machines" build.keychain -p | openssl x509 -text -noout | grep -E "(Subject:|CN=)" || echo "Could not parse certificate"
# Set the correct signing identity
echo "APPLE_SIGNING_IDENTITY=Developer ID Application: Learning Machines LLC (DJ6XS33FX8)" >> $GITHUB_ENV
echo "APPLE_SIGNING_IDENTITY=Developer ID Application: Learning Machines LLC (DJ6XS33FX8)" >> "$GITHUB_ENV"
echo "Proceeding with identity: Developer ID Application: Learning Machines LLC (DJ6XS33FX8)"
# Also set the team ID
echo "APPLE_DEVELOPMENT_TEAM=DJ6XS33FX8" >> $GITHUB_ENV
echo "APPLE_DEVELOPMENT_TEAM=DJ6XS33FX8" >> "$GITHUB_ENV"
- name: Pre-build frontend to avoid Tauri build issues
run: |
@@ -200,6 +201,7 @@ jobs:
npx nx run artcraft:build
echo "Checking build output..."
# shellcheck disable=SC2012
ls -la apps/artcraft/dist/ | head -10
# Update Tauri config to skip the build (since we already built)
@@ -44,6 +44,7 @@ jobs:
node-version: lts/*
- name: install frontend dependencies
shell: pwsh
run: |
# Navigate to the frontend directory to install dependencies
cd ./frontend
@@ -63,6 +64,7 @@ jobs:
npm list --depth=0 | findstr nx
- name: Pre-build frontend to avoid Tauri build issues
shell: pwsh
run: |
# Build the frontend app from the correct directory
cd ./frontend
+24
View File
@@ -0,0 +1,24 @@
# Builds and tests the workspace on FreeBSD, inside a FreeBSD VM on a Linux runner
# (GitHub has no FreeBSD runners).
name: FreeBSD
# The VM build is slow, so it runs nightly on main and on pushes to `release`, not on pull requests.
on:
schedule:
- cron: "27 4 * * *"
push:
branches: [release]
workflow_dispatch:
concurrency:
group: freebsd-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
freebsd:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main
+23
View File
@@ -0,0 +1,23 @@
# Quick static checks for the release pipeline (seconds, no Rust build): workflow syntax,
# packaging shell/PowerShell scripts, and the Linux desktop/AppStream/Flatpak metadata.
name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**"]
pull_request:
paths: [".github/workflows/**", "packaging/**"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: packaging-lint-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
# Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos.
uses: storytold/craft-common-actions/.github/workflows/packaging-lint.yml@main
+1
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
@@ -6,6 +6,7 @@ use enums::common::generation::common_bitrate::CommonBitrate;
use enums::common::generation::common_quality::CommonQuality;
use enums::common::generation::common_resolution::CommonResolution;
use enums::common::generation::common_video_model::CommonVideoModel;
use enums::common::generation::common_video_output_format::CommonVideoOutputFormat;
use tokens::tokens::characters::CharacterToken;
use tokens::tokens::media_files::MediaFileToken;
@@ -55,6 +56,11 @@ pub struct OmniGenVideoCostAndGenerateRequest {
/// Not all models support this; models that don't simply ignore it.
pub bitrate: Option<CommonBitrate>,
/// Output container for Seedance 2.5 (including Ultra). Other models ignore it.
/// Use "mp4" or "mov" (QuickTime). Omitted or null defaults to MP4.
#[serde(rename = "output_format", skip_serializing_if = "Option::is_none")]
pub maybe_output_format: Option<CommonVideoOutputFormat>,
/// The quality to use.
pub quality: Option<CommonQuality>,
@@ -2,6 +2,7 @@ use enums::common::generation::common_aspect_ratio::CommonAspectRatio;
use enums::common::generation::common_quality::CommonQuality;
use enums::common::generation::common_resolution::CommonResolution;
use enums::common::generation::common_video_model::CommonVideoModel;
use enums::common::generation::common_video_output_format::CommonVideoOutputFormat;
use enums::common::generation::model_creator::ModelCreator;
use enums::common::generation_provider::GenerationProvider;
use serde_derive::{Deserialize, Serialize};
@@ -156,6 +157,12 @@ pub struct OmniGenVideoModelDetails {
#[serde(skip_serializing_if = "Option::is_none")]
pub bitrate_default: Option<CommonBitrate>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output_format_options: Option<Vec<CommonVideoOutputFormat>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output_format_default: Option<CommonVideoOutputFormat>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quality_options: Option<Vec<CommonQuality>>,
@@ -229,6 +236,8 @@ impl Default for OmniGenVideoModelDetails {
resolution_default: None,
bitrate_options: None,
bitrate_default: None,
output_format_options: None,
output_format_default: None,
quality_options: None,
default_quality: None,
duration_seconds_min: None,
@@ -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,
}
@@ -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;
@@ -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())
}
@@ -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.
@@ -7,3 +7,4 @@ pub mod media_files;
pub mod prompts;
pub mod stripe_artcraft;
pub mod subscriptions;
pub mod users;
@@ -158,6 +158,10 @@ pub struct OmniGenVideoModelDetails {
#[serde(default)]
pub bitrate_default: Option<ApiClientBitrate>,
#[serde(default)]
pub output_format_options: Option<Vec<String>>,
#[serde(default)]
pub output_format_default: Option<String>,
#[serde(default)]
pub quality_options: Option<Vec<ApiClientQuality>>,
#[serde(default)]
pub default_quality: Option<ApiClientQuality>,
@@ -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)
}
}
@@ -0,0 +1,2 @@
pub mod create_login_challenge;
pub mod poll_login_challenge;
@@ -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,
})
}
}
@@ -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;
@@ -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>,
}
@@ -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
}
}
@@ -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
}
}
@@ -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)
}
}
@@ -0,0 +1,151 @@
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::constants::USER_AGENT;
/// 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 = Client::builder();
if matches!(api_host, ApiHost::Localhost { .. }) {
builder = builder.no_proxy();
}
let client = builder
.timeout(Duration::from_secs(15))
.redirect(reqwest::redirect::Policy::none())
.user_agent(USER_AGENT)
.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 {}
@@ -7,3 +7,4 @@ pub (crate) mod http_get_anonymous;
pub mod api_host;
pub mod constants;
pub mod status_codes;
pub mod login_challenge_client;
@@ -1,10 +1,20 @@
use serde_derive::{Deserialize, Serialize};
/// Common quality levels you can specify when enqueuing a generation.
/// Not every model will use this; models that don't simply ignore it.
/// Not every model will use this; models that don't simply ignore it, and models that only
/// offer a subset of tiers clamp to the nearest tier they support.
///
/// Serialized names mirror the server's `CommonQuality` so the two convert via serde.
#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RouterQuality {
/// Let the model choose. Models without a native "auto" use their default tier.
Auto,
/// Highest tier (GPT Image 2.5 `max`).
Max,
/// Between High and Max (GPT Image 2.5 `xhigh`).
#[serde(rename = "xhigh")]
XHigh,
High,
Medium,
Low,
@@ -151,8 +151,11 @@ fn to_resolution_enum(r: RouterResolution) -> CommonResolutionEnum {
fn to_quality_enum(q: RouterQuality) -> CommonQualityEnum {
match q {
RouterQuality::Low => CommonQualityEnum::Low,
RouterQuality::Medium => CommonQualityEnum::Medium,
RouterQuality::Auto => CommonQualityEnum::Auto,
RouterQuality::Max => CommonQualityEnum::Max,
RouterQuality::XHigh => CommonQualityEnum::XHigh,
RouterQuality::High => CommonQualityEnum::High,
RouterQuality::Medium => CommonQualityEnum::Medium,
RouterQuality::Low => CommonQualityEnum::Low,
}
}
@@ -36,7 +36,7 @@ impl ArtcraftGptImage1CostState {
}
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
let quality = self.quality.unwrap_or(CommonQualityEnum::High);
let quality = clamp_to_supported_quality(self.quality);
let is_square = is_square_or_none(self.aspect_ratio);
let output_cost_per_image: u64 = match (quality, is_square) {
@@ -45,6 +45,8 @@ impl ArtcraftGptImage1CostState {
(CommonQualityEnum::Medium, false) => 7,
(CommonQualityEnum::High, true) => 17,
(CommonQualityEnum::High, false) => 25,
// Clamped away above.
(CommonQualityEnum::Auto | CommonQualityEnum::XHigh | CommonQualityEnum::Max, _) => unreachable!(),
};
let output_cost = output_cost_per_image * self.num_images as u64;
@@ -63,6 +65,20 @@ impl ArtcraftGptImage1CostState {
}
}
/// GPT Image 1 only offers low / medium / high. `auto` prices as the default (high) and the
/// higher GPT Image 2.5 tiers clamp down to high, matching the Fal request planner.
fn clamp_to_supported_quality(quality: Option<CommonQualityEnum>) -> CommonQualityEnum {
match quality {
Some(CommonQualityEnum::Low) => CommonQualityEnum::Low,
Some(CommonQualityEnum::Medium) => CommonQualityEnum::Medium,
Some(CommonQualityEnum::High)
| Some(CommonQualityEnum::XHigh)
| Some(CommonQualityEnum::Max)
| Some(CommonQualityEnum::Auto)
| None => CommonQualityEnum::High,
}
}
fn is_square_or_none(aspect_ratio: Option<CommonAspectRatioEnum>) -> bool {
use CommonAspectRatioEnum as Ar;
matches!(
@@ -37,7 +37,7 @@ impl ArtcraftGptImage1p5CostState {
}
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
let quality = self.quality.unwrap_or(CommonQualityEnum::High);
let quality = clamp_to_supported_quality(self.quality);
let size = size_bucket(self.aspect_ratio);
let cost_per_image: u64 = match (quality, size) {
@@ -50,6 +50,8 @@ impl ArtcraftGptImage1p5CostState {
(CommonQualityEnum::High, SizeBucket::Square) => 14,
(CommonQualityEnum::High, _) => 20,
// Clamped away above.
(CommonQualityEnum::Auto | CommonQualityEnum::XHigh | CommonQualityEnum::Max, _) => unreachable!(),
};
let cost_in_usd_cents = cost_per_image * self.num_images as u64;
@@ -65,6 +67,20 @@ impl ArtcraftGptImage1p5CostState {
}
}
/// GPT Image 1.5 only offers low / medium / high. `auto` prices as the default (high) and the
/// higher GPT Image 2.5 tiers clamp down to high, matching the Fal request planner.
fn clamp_to_supported_quality(quality: Option<CommonQualityEnum>) -> CommonQualityEnum {
match quality {
Some(CommonQualityEnum::Low) => CommonQualityEnum::Low,
Some(CommonQualityEnum::Medium) => CommonQualityEnum::Medium,
Some(CommonQualityEnum::High)
| Some(CommonQualityEnum::XHigh)
| Some(CommonQualityEnum::Max)
| Some(CommonQualityEnum::Auto)
| None => CommonQualityEnum::High,
}
}
fn size_bucket(aspect_ratio: Option<CommonAspectRatioEnum>) -> SizeBucket {
use CommonAspectRatioEnum as Ar;
match aspect_ratio {
@@ -42,7 +42,7 @@ impl ArtcraftGptImage2CostState {
}
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
let quality = self.quality.unwrap_or(CommonQualityEnum::High);
let quality = clamp_to_supported_quality(self.quality);
let size = size_bucket(self.aspect_ratio);
let cost_per_image: u64 = match (quality, size) {
@@ -62,6 +62,8 @@ impl ArtcraftGptImage2CostState {
| (CommonQualityEnum::High, SizeBucket::Portrait4x3) => 15,
(CommonQualityEnum::High, SizeBucket::Landscape16x9)
| (CommonQualityEnum::High, SizeBucket::Portrait16x9) => 16,
// Clamped away above.
(CommonQualityEnum::Auto | CommonQualityEnum::XHigh | CommonQualityEnum::Max, _) => unreachable!(),
};
let cost_in_usd_cents = cost_per_image * self.num_images as u64;
@@ -77,6 +79,20 @@ impl ArtcraftGptImage2CostState {
}
}
/// GPT Image 2 only offers low / medium / high. `auto` prices as the default (high) and the
/// higher GPT Image 2.5 tiers clamp down to high, matching the Fal request planner.
fn clamp_to_supported_quality(quality: Option<CommonQualityEnum>) -> CommonQualityEnum {
match quality {
Some(CommonQualityEnum::Low) => CommonQualityEnum::Low,
Some(CommonQualityEnum::Medium) => CommonQualityEnum::Medium,
Some(CommonQualityEnum::High)
| Some(CommonQualityEnum::XHigh)
| Some(CommonQualityEnum::Max)
| Some(CommonQualityEnum::Auto)
| None => CommonQualityEnum::High,
}
}
/// Mirrors v1's `plan_image_size` for GPT Image 2 — see the v1 file
/// `plan_generate_image_artcraft_gpt_image_2.rs::plan_image_size`.
fn size_bucket(aspect_ratio: Option<CommonAspectRatioEnum>) -> SizeBucket {
@@ -8,25 +8,27 @@ use fal_client::requests::api::image::common::gpt_image_2p5::gpt_image_2p5_image
use crate::generate::generate_image::image_generation_cost_estimate::ImageGenerationCostEstimate;
/// Artcraft price per output image, in hundredths of a US cent, by output dimensions and
/// quality (`[low, medium, high]`). Rows are stored landscape-first; portrait orientations of
/// the same dimensions price identically. Dimensions come from the aspect ratio preset and
/// resolution tier the same way the Fal request builder derives them.
const OUTPUT_IMAGE_PRICE_TABLE: &[(u32, u32, [u64; 3])] = &[
/// quality (`[low, medium, high, xhigh, max]`). Each cell is the `fal_client` GPT Image 2.5
/// estimate for that size and tier with a 10% markup, rounded up. Rows are stored
/// landscape-first; portrait orientations of the same dimensions price identically.
/// Dimensions come from the aspect ratio preset and resolution tier the same way the Fal
/// request builder derives them.
const OUTPUT_IMAGE_PRICE_TABLE: &[(u32, u32, [u64; 5])] = &[
// 1:1
(1024, 1024, [ 65, 152, 582]),
(2048, 2048, [103, 239, 919]),
(2880, 2880, [151, 352, 1357]),
(1024, 1024, [ 65, 152, 582, 1034, 2327]),
(2048, 2048, [103, 239, 919, 1633, 3672]),
(2880, 2880, [151, 352, 1357, 2412, 5426]),
// 4:3
(1024, 768, [ 46, 105, 400]),
(2048, 1536, [ 73, 170, 652]),
(3072, 2304, [120, 279, 1073]),
(3312, 2480, [134, 311, 1194]),
(1024, 768, [ 46, 105, 400, 710, 1597]),
(2048, 1536, [ 73, 170, 652, 1159, 2605]),
(3072, 2304, [120, 279, 1073, 1906, 4287]),
(3312, 2480, [134, 311, 1194, 2122, 4773]),
// 16:9
(1088, 608, [ 32, 75, 285]),
(1920, 1080, [ 49, 114, 436]),
(2048, 1152, [ 53, 121, 467]),
(3072, 1728, [ 87, 204, 783]),
(3840, 2160, [124, 286, 1102]),
(1088, 608, [ 32, 75, 285, 506, 1139]),
(1920, 1080, [ 49, 114, 436, 775, 1743]),
(2048, 1152, [ 53, 121, 467, 830, 1865]),
(3072, 1728, [ 87, 204, 783, 1390, 3127]),
(3840, 2160, [124, 286, 1102, 1957, 4404]),
];
/// Artcraft price per reference image on an edit request, in hundredths of a US cent.
@@ -55,7 +57,8 @@ impl ArtcraftGptImage2p5CostInputs {
}
/// Per-image price rounded up to whole cents, times the batch size. Quality defaults to
/// high. Without an aspect ratio, text-to-image prices as landscape 4:3 and edit as auto,
/// high, and `auto` is priced as high (the documented default the model falls back to).
/// Without an aspect ratio, text-to-image prices as landscape 4:3 and edit as auto,
/// matching the Fal defaults the request would fall back to.
pub fn estimate_cost(&self) -> ImageGenerationCostEstimate {
let quality = self.quality.unwrap_or(CommonQualityEnum::High);
@@ -91,11 +94,13 @@ fn output_image_price(quality: CommonQualityEnum, width: u32, height: u32) -> u6
match quality {
CommonQualityEnum::Low => prices[0],
CommonQualityEnum::Medium => prices[1],
CommonQualityEnum::High => prices[2],
CommonQualityEnum::High | CommonQualityEnum::Auto => prices[2],
CommonQualityEnum::XHigh => prices[3],
CommonQualityEnum::Max => prices[4],
}
}
fn lookup_price_row(width: u32, height: u32) -> Option<[u64; 3]> {
fn lookup_price_row(width: u32, height: u32) -> Option<[u64; 5]> {
let long_edge = width.max(height);
let short_edge = width.min(height);
OUTPUT_IMAGE_PRICE_TABLE.iter()
@@ -176,6 +181,18 @@ mod tests {
(Some(Ar::Auto4k), Some(R::OneK), [2, 3, 12]),
];
// (aspect_ratio, resolution, [xhigh, max]) — cents per image, text-to-image
const TEXT_GRID_UPPER_TIERS: &[(Option<Ar>, Option<R>, [u64; 2])] = &[
(None, None, [ 8, 16]), // landscape 4:3 default
(Some(Ar::Square), None, [11, 24]),
(Some(Ar::Square), Some(R::TwoK), [17, 37]),
(Some(Ar::Square), Some(R::FourK), [25, 55]),
(Some(Ar::WideSixteenByNine), None, [ 8, 18]),
(Some(Ar::WideSixteenByNine), Some(R::OneK), [ 6, 12]),
(Some(Ar::TallNineBySixteen), Some(R::FourK), [20, 45]),
(Some(Ar::Auto), None, [20, 45]),
];
mod text_to_image_tests {
use super::*;
@@ -189,11 +206,32 @@ mod tests {
}
}
#[test]
fn upper_tier_grid() {
for &(aspect_ratio, resolution, expected) in TEXT_GRID_UPPER_TIERS {
for (quality, expected) in [Q::XHigh, Q::Max].into_iter().zip(expected) {
let actual = cents(make_inputs(0, Some(quality), aspect_ratio, resolution, 1));
assert_eq!(actual, expected, "{aspect_ratio:?} {resolution:?} {quality:?}");
}
}
}
#[test]
fn quality_defaults_to_high() {
assert_eq!(cents(make_inputs(0, None, Some(Ar::Square), None, 1)), 6);
}
#[test]
fn auto_prices_as_high() {
for &(aspect_ratio, resolution, _) in TEXT_GRID {
assert_eq!(
cents(make_inputs(0, Some(Q::Auto), aspect_ratio, resolution, 1)),
cents(make_inputs(0, Some(Q::High), aspect_ratio, resolution, 1)),
"{aspect_ratio:?} {resolution:?}",
);
}
}
#[test]
fn batch_multiplies_per_image_cents() {
for &(aspect_ratio, resolution, _) in TEXT_GRID {
@@ -265,7 +303,7 @@ mod tests {
#[test]
fn prices_rise_with_quality_and_size() {
for &(_, _, prices) in OUTPUT_IMAGE_PRICE_TABLE {
assert!(prices[0] < prices[1] && prices[1] < prices[2], "{prices:?}");
assert!(prices.windows(2).all(|pair| pair[0] < pair[1]), "{prices:?}");
}
assert!(output_image_price(Q::High, 1024, 1024) < output_image_price(Q::High, 2048, 2048));
assert!(output_image_price(Q::High, 2048, 2048) < output_image_price(Q::High, 2880, 2880));
@@ -100,11 +100,17 @@ fn plan_num_images(
}
}
/// This endpoint only offers low / medium / high. `auto` falls back to Fal's default (`high`)
/// and the higher GPT Image 2.5 tiers (`xhigh`, `max`) clamp down to `high`.
fn plan_quality(quality: Option<RouterQuality>) -> PlannedQuality {
match quality {
Some(RouterQuality::Low) => PlannedQuality::Low,
Some(RouterQuality::Medium) => PlannedQuality::Medium,
Some(RouterQuality::High) | None => PlannedQuality::High,
Some(RouterQuality::High)
| Some(RouterQuality::XHigh)
| Some(RouterQuality::Max)
| Some(RouterQuality::Auto)
| None => PlannedQuality::High,
}
}
@@ -337,6 +343,10 @@ mod tests {
(Some(RouterQuality::Low), "Some(Low)"),
(Some(RouterQuality::Medium), "Some(Medium)"),
(Some(RouterQuality::High), "Some(High)"),
// Tiers this endpoint lacks clamp to high.
(Some(RouterQuality::Auto), "Some(High)"),
(Some(RouterQuality::XHigh), "Some(High)"),
(Some(RouterQuality::Max), "Some(High)"),
];
for (quality, expected) in cases {
@@ -100,11 +100,17 @@ fn plan_num_images(
}
}
/// This endpoint only offers low / medium / high. `auto` falls back to Fal's default (`high`)
/// and the higher GPT Image 2.5 tiers (`xhigh`, `max`) clamp down to `high`.
fn plan_quality(quality: Option<RouterQuality>) -> PlannedQuality {
match quality {
Some(RouterQuality::Low) => PlannedQuality::Low,
Some(RouterQuality::Medium) => PlannedQuality::Medium,
Some(RouterQuality::High) | None => PlannedQuality::High,
Some(RouterQuality::High)
| Some(RouterQuality::XHigh)
| Some(RouterQuality::Max)
| Some(RouterQuality::Auto)
| None => PlannedQuality::High,
}
}
@@ -337,6 +343,10 @@ mod tests {
(Some(RouterQuality::Low), "Some(Low)"),
(Some(RouterQuality::Medium), "Some(Medium)"),
(Some(RouterQuality::High), "Some(High)"),
// Tiers this endpoint lacks clamp to high.
(Some(RouterQuality::Auto), "Some(High)"),
(Some(RouterQuality::XHigh), "Some(High)"),
(Some(RouterQuality::Max), "Some(High)"),
];
for (quality, expected) in cases {
@@ -106,11 +106,17 @@ fn plan_num_images(
}
}
/// This endpoint only offers low / medium / high. `auto` falls back to Fal's default (`high`)
/// and the higher GPT Image 2.5 tiers (`xhigh`, `max`) clamp down to `high`.
fn plan_quality(quality: Option<RouterQuality>) -> PlannedQuality {
match quality {
Some(RouterQuality::Low) => PlannedQuality::Low,
Some(RouterQuality::Medium) => PlannedQuality::Medium,
Some(RouterQuality::High) | None => PlannedQuality::High,
Some(RouterQuality::High)
| Some(RouterQuality::XHigh)
| Some(RouterQuality::Max)
| Some(RouterQuality::Auto)
| None => PlannedQuality::High,
}
}
@@ -362,6 +368,10 @@ mod tests {
(Some(RouterQuality::Low), "Some(Low)"),
(Some(RouterQuality::Medium), "Some(Medium)"),
(Some(RouterQuality::High), "Some(High)"),
// Tiers this endpoint lacks clamp to high.
(Some(RouterQuality::Auto), "Some(High)"),
(Some(RouterQuality::XHigh), "Some(High)"),
(Some(RouterQuality::Max), "Some(High)"),
];
for (quality, expected) in cases {
@@ -82,13 +82,16 @@ fn plan_num_images(
}
}
/// The router only exposes low / medium / high; GPT Image 2.5's `xhigh` and `max` tiers are
/// not reachable through it. Fal's default (`high`) applies when unspecified.
/// GPT Image 2.5 supports every router tier natively. Fal's default (`high`) applies when
/// unspecified.
fn plan_quality(quality: Option<RouterQuality>) -> GptImage2p5Quality {
match quality {
Some(RouterQuality::Low) => GptImage2p5Quality::Low,
Some(RouterQuality::Medium) => GptImage2p5Quality::Medium,
Some(RouterQuality::Auto) => GptImage2p5Quality::Auto,
Some(RouterQuality::Max) => GptImage2p5Quality::Max,
Some(RouterQuality::XHigh) => GptImage2p5Quality::XHigh,
Some(RouterQuality::High) | None => GptImage2p5Quality::High,
Some(RouterQuality::Medium) => GptImage2p5Quality::Medium,
Some(RouterQuality::Low) => GptImage2p5Quality::Low,
}
}
@@ -220,9 +223,12 @@ mod tests {
fn quality_maps_exhaustively_for_text_and_edit() {
let cases = [
(None, "Some(High)"),
(Some(RouterQuality::Low), "Some(Low)"),
(Some(RouterQuality::Medium), "Some(Medium)"),
(Some(RouterQuality::Auto), "Some(Auto)"),
(Some(RouterQuality::Max), "Some(Max)"),
(Some(RouterQuality::XHigh), "Some(XHigh)"),
(Some(RouterQuality::High), "Some(High)"),
(Some(RouterQuality::Medium), "Some(Medium)"),
(Some(RouterQuality::Low), "Some(Low)"),
];
for (quality, expected) in cases {
let text = unwrap_t2i(plan_gpt_image_2p5_params(&GenerateImageRequestBuilder { quality, ..base_builder() }));
@@ -53,6 +53,9 @@ mod tests {
(Some(Q::Low), Some(Ar::Square), None, 1, 1),
(Some(Q::Medium), Some(Ar::Square), None, 1, 2),
(Some(Q::High), Some(Ar::Square), None, 1, 6),
(Some(Q::Auto), Some(Ar::Square), None, 1, 6), // auto is priced as high
(Some(Q::XHigh), Some(Ar::Square), None, 1, 10),
(Some(Q::Max), Some(Ar::Square), None, 1, 22),
(Some(Q::High), Some(Ar::Square), None, 4, 24),
(Some(Q::High), Some(Ar::SquareHd), None, 1, 9),
(Some(Q::High), Some(Ar::Square), Some(R::TwoK), 1, 9),
@@ -53,6 +53,9 @@ mod tests {
(Some(Q::Low), Some(Ar::Square), None, 1, 1),
(Some(Q::Medium), Some(Ar::Square), None, 1, 2),
(Some(Q::High), Some(Ar::Square), None, 1, 6),
(Some(Q::Auto), Some(Ar::Square), None, 1, 6), // auto is priced as high
(Some(Q::XHigh), Some(Ar::Square), None, 1, 10),
(Some(Q::Max), Some(Ar::Square), None, 1, 22),
(Some(Q::High), Some(Ar::Square), None, 4, 24),
(Some(Q::High), Some(Ar::SquareHd), None, 1, 9),
(Some(Q::High), Some(Ar::Square), Some(R::TwoK), 1, 9),
@@ -122,10 +122,14 @@ pub(crate) fn plan_quality(quality: Option<RouterQuality>) -> Option<GenerateMid
// Kinovi pricing — pass through whatever the caller asked for, and let
// `None` ride Midjourney's server-side default.
match quality {
None => None,
// `auto` has no Midjourney equivalent; leave it to the provider default.
None | Some(RouterQuality::Auto) => None,
Some(RouterQuality::Low) => Some(GenerateMidjourneyV7Quality::Quarter),
Some(RouterQuality::Medium) => Some(GenerateMidjourneyV7Quality::Half),
Some(RouterQuality::High) => Some(GenerateMidjourneyV7Quality::Full),
// Midjourney tops out at full quality; the higher GPT Image tiers clamp to it.
Some(RouterQuality::High)
| Some(RouterQuality::XHigh)
| Some(RouterQuality::Max) => Some(GenerateMidjourneyV7Quality::Full),
}
}
@@ -110,10 +110,14 @@ pub(crate) fn plan_aspect_ratio(
pub(crate) fn plan_quality(quality: Option<RouterQuality>) -> Option<GenerateMidjourneyV7NijiQuality> {
match quality {
None => None,
// `auto` has no Midjourney equivalent; leave it to the provider default.
None | Some(RouterQuality::Auto) => None,
Some(RouterQuality::Low) => Some(GenerateMidjourneyV7NijiQuality::Quarter),
Some(RouterQuality::Medium) => Some(GenerateMidjourneyV7NijiQuality::Half),
Some(RouterQuality::High) => Some(GenerateMidjourneyV7NijiQuality::Full),
// Midjourney tops out at full quality; the higher GPT Image tiers clamp to it.
Some(RouterQuality::High)
| Some(RouterQuality::XHigh)
| Some(RouterQuality::Max) => Some(GenerateMidjourneyV7NijiQuality::Full),
}
}
@@ -110,10 +110,14 @@ pub(crate) fn plan_aspect_ratio(
pub(crate) fn plan_quality(quality: Option<RouterQuality>) -> Option<GenerateMidjourneyV8Quality> {
match quality {
None => None,
// `auto` has no Midjourney equivalent; leave it to the provider default.
None | Some(RouterQuality::Auto) => None,
Some(RouterQuality::Low) => Some(GenerateMidjourneyV8Quality::Quarter),
Some(RouterQuality::Medium) => Some(GenerateMidjourneyV8Quality::Half),
Some(RouterQuality::High) => Some(GenerateMidjourneyV8Quality::Full),
// Midjourney tops out at full quality; the higher GPT Image tiers clamp to it.
Some(RouterQuality::High)
| Some(RouterQuality::XHigh)
| Some(RouterQuality::Max) => Some(GenerateMidjourneyV8Quality::Full),
}
}
@@ -77,6 +77,7 @@ pub fn build_artcraft_omni_video_request(
resolution,
aspect_ratio,
bitrate,
maybe_output_format: None,
duration_seconds: duration_seconds.map(|d| d as u16),
video_batch_count: Some(batch_count),
negative_prompt: None,
@@ -59,6 +59,7 @@ mod tests {
resolution: None,
aspect_ratio: None,
bitrate: None,
maybe_output_format: None,
quality: None,
duration_seconds: Some(5),
video_batch_count: Some(1),
@@ -5,6 +5,10 @@ use artcraft_router::api::router_quality::RouterQuality;
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CommonQuality {
Auto,
Max,
#[serde(rename = "xhigh")]
XHigh,
High,
Medium,
Low,
@@ -13,6 +17,9 @@ pub enum CommonQuality {
impl CommonQuality {
pub fn to_artcraft_router_type(&self) -> RouterQuality {
match self {
CommonQuality::Auto => RouterQuality::Auto,
CommonQuality::Max => RouterQuality::Max,
CommonQuality::XHigh => RouterQuality::XHigh,
CommonQuality::High => RouterQuality::High,
CommonQuality::Medium => RouterQuality::Medium,
CommonQuality::Low => RouterQuality::Low,
@@ -30,6 +30,9 @@ pub fn convert_aspect_ratio(value: EnumsAspectRatio) -> RouterAspectRatio {
pub fn convert_quality(value: EnumsQuality) -> RouterQuality {
match value {
EnumsQuality::Auto => RouterQuality::Auto,
EnumsQuality::Max => RouterQuality::Max,
EnumsQuality::XHigh => RouterQuality::XHigh,
EnumsQuality::High => RouterQuality::High,
EnumsQuality::Medium => RouterQuality::Medium,
EnumsQuality::Low => RouterQuality::Low,
@@ -552,3 +552,25 @@ impl From<OmniGenImageModelDetails> for ListImageModelsModelDetails {
}
}
}
#[cfg(test)]
mod catalog_parity_tests {
use super::*;
use serde_json::json;
#[test]
fn gpt_image_2p5_quality_tiers_survive_the_desktop_listing_boundary() {
for model in ["gpt_image_2p5_flare", "gpt_image_2p5_sunburst"] {
let source = json!({
"model": model,
"quality_options": ["auto", "max", "xhigh", "high", "medium", "low", "future_quality"],
"default_quality": "high",
"resolution_options": ["one_k", "two_k", "three_k", "four_k"],
"resolution_default": "one_k"
});
let client: OmniGenImageModelDetails = serde_json::from_value(source.clone()).unwrap();
let desktop = serde_json::to_value(ListImageModelsModelDetails::from(client)).unwrap();
assert_eq!(desktop, source);
}
}
}
@@ -597,6 +597,10 @@ pub struct ListVideoModelsModelDetails {
#[serde(skip_serializing_if = "Option::is_none")]
pub bitrate_default: Option<ListVideoModelsBitrate>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output_format_options: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output_format_default: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub quality_options: Option<Vec<ListVideoModelsQuality>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub default_quality: Option<ListVideoModelsQuality>,
@@ -655,6 +659,8 @@ impl From<OmniGenVideoModelDetails> for ListVideoModelsModelDetails {
resolution_default: v.resolution_default.map(Into::into),
bitrate_options: v.bitrate_options.map(|items| items.into_iter().map(Into::into).collect()),
bitrate_default: v.bitrate_default.map(Into::into),
output_format_options: v.output_format_options,
output_format_default: v.output_format_default,
quality_options: v.quality_options.map(|items| items.into_iter().map(Into::into).collect()),
default_quality: v.default_quality.map(Into::into),
duration_seconds_min: v.duration_seconds_min,
@@ -670,3 +676,26 @@ impl From<OmniGenVideoModelDetails> for ListVideoModelsModelDetails {
}
}
}
#[cfg(test)]
mod catalog_parity_tests {
use super::*;
use serde_json::json;
#[test]
fn wan_and_output_formats_survive_the_desktop_listing_boundary() {
for model in ["wan_3p0", "wan_3p0_prime", "seedance_2p5", "seedance_2p5_u", "future_video"] {
let source = json!({
"model": model,
"output_format_options": ["mp4", "mov", "future_container"],
"output_format_default": "mp4",
"batch_size_options": [1, 2, 3, 4],
"duration_seconds_max": 30,
"video_references_max": 5
});
let client: OmniGenVideoModelDetails = serde_json::from_value(source.clone()).unwrap();
let desktop = serde_json::to_value(ListVideoModelsModelDetails::from(client)).unwrap();
assert_eq!(desktop, source);
}
}
}
@@ -123,6 +123,31 @@ mod tests {
use super::*;
use serde_json::json;
#[test]
fn catalog_parity_new_models_and_options_reach_the_api_unchanged() {
for model in ["gpt_image_2p5_flare", "gpt_image_2p5_sunburst"] {
for quality in ["auto", "max", "xhigh", "high", "medium", "low"] {
let source = json!({"model": model, "quality": quality, "resolution": "four_k"});
let request: OmniRequest = serde_json::from_value(source.clone()).unwrap();
assert!(request.uses_artcraft());
assert!(!request.uses_legacy_image_endpoint());
assert_eq!(Value::Object(request.api_fields(Modality::Image)), source);
}
}
for model in ["wan_3p0", "wan_3p0_prime", "seedance_2p5", "seedance_2p5_u"] {
let source = json!({
"model": model, "duration_seconds": 15, "resolution": "ten_eighty_p",
"output_format": "mov", "generate_audio": true,
"reference_image_media_tokens": ["mf_image"],
"reference_video_media_tokens": ["mf_video"],
"reference_audio_media_tokens": ["mf_audio"]
});
let request: OmniRequest = serde_json::from_value(source.clone()).unwrap();
assert!(request.uses_artcraft());
assert_eq!(Value::Object(request.api_fields(Modality::Video)), source);
}
}
#[test]
fn future_model_and_options_survive_without_desktop_metadata() {
let request: OmniRequest = serde_json::from_value(json!({
@@ -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");
}
}
+14
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,
@@ -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.
@@ -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;
@@ -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;
@@ -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(())
}
@@ -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
}
@@ -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
}
@@ -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}),
)
}
@@ -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
}
@@ -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
}
@@ -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
}
@@ -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));
}
}
+1 -1
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";
+1 -1
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",
+1 -1
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",
+29 -14
View File
@@ -1,7 +1,20 @@
use std::env;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
pub fn main() {
println!("cargo:rerun-if-env-changed=DATABASE_URL");
println!("cargo:rerun-if-env-changed=SQLX_OFFLINE");
if let Ok(url) = env::var("DATABASE_URL") {
println!("cargo:rustc-env=DATABASE_URL={}", url);
return;
}
if env::var("SQLX_OFFLINE").as_deref() == Ok("true") || env::var("SQLX_OFFLINE").as_deref() == Ok("1") {
println!("cargo:rustc-env=SQLX_OFFLINE=true");
return;
}
// NB: This should help JetBrains' RustRover from highlighting failing query macros,
// but we do not want to interfere with the following:
//
@@ -14,27 +27,29 @@ pub fn main() {
Some("unix") => unix_temp_database_pathing(),
Some("windows") => windows_temp_database_pathing(),
_ => {
println!("cargo:warning=Unsupported target family, using Unix temp database pathing.");
unix_temp_database_pathing();
println!("cargo:rustc-env=SQLX_OFFLINE=true");
},
}
}
fn unix_temp_database_pathing() {
println!("cargo:rustc-env=DATABASE_URL=sqlite:/tmp/tasks.sqlite");
println!("cargo:rerun-if-changed=/tmp/tasks.sqlite");
if Path::new("/tmp/tasks.sqlite").exists() {
println!("cargo:rustc-env=DATABASE_URL=sqlite:/tmp/tasks.sqlite");
} else {
println!("cargo:rustc-env=SQLX_OFFLINE=true");
}
}
fn windows_temp_database_pathing() {
if let Ok(local_app_data) = env::var("LOCALAPPDATA") {
let path = PathBuf::from(local_app_data);
let path = path.join("Temp\\tasks.sqlite");
let path = path
.to_str()
.expect("path should be valid")
.to_string();
println!("cargo:warning=LocalAppData path: {}", path);
println!("cargo:rustc-env=DATABASE_URL=sqlite:{}", path);
} else {
panic!("LOCALAPPDATA environment variable not set");
let path = PathBuf::from(local_app_data).join("Temp\\tasks.sqlite");
if path.exists() {
let path_str = path.to_str().expect("path should be valid");
println!("cargo:warning=LocalAppData path: {}", path_str);
println!("cargo:rustc-env=DATABASE_URL=sqlite:{}", path_str);
return;
}
}
println!("cargo:rustc-env=SQLX_OFFLINE=true");
}
@@ -192,6 +192,12 @@ pub enum InferenceModelType {
Kling3p0Pro,
#[serde(rename = "happy_horse_1p0")]
HappyHorse1p0,
#[serde(rename = "wan_3p0")]
Wan3p0,
#[serde(rename = "wan_3p0_prime")]
Wan3p0Prime,
#[serde(rename = "minimax_h3")]
MinimaxH3,
#[serde(rename = "minimax_h3_turbo")]
@@ -394,6 +400,8 @@ impl InferenceModelType {
Self::Kling3p0Standard => "kling_3p0_standard",
Self::Kling3p0Pro => "kling_3p0_pro",
Self::HappyHorse1p0 => "happy_horse_1p0",
Self::Wan3p0 => "wan_3p0",
Self::Wan3p0Prime => "wan_3p0_prime",
Self::MinimaxH3 => "minimax_h3",
Self::MinimaxH3Turbo => "minimax_h3_turbo",
Self::MinimaxH3Ultra => "minimax_h3_ultra",
@@ -534,6 +542,8 @@ impl InferenceModelType {
"kling_3p0_standard" => Ok(Self::Kling3p0Standard),
"kling_3p0_pro" => Ok(Self::Kling3p0Pro),
"happy_horse_1p0" => Ok(Self::HappyHorse1p0),
"wan_3p0" => Ok(Self::Wan3p0),
"wan_3p0_prime" => Ok(Self::Wan3p0Prime),
"minimax_h3" => Ok(Self::MinimaxH3),
"minimax_h3_turbo" => Ok(Self::MinimaxH3Turbo),
"minimax_h3_ultra" => Ok(Self::MinimaxH3Ultra),
@@ -678,6 +688,8 @@ impl InferenceModelType {
Self::Kling3p0Standard,
Self::Kling3p0Pro,
Self::HappyHorse1p0,
Self::Wan3p0,
Self::Wan3p0Prime,
Self::MinimaxH3,
Self::MinimaxH3Turbo,
Self::MinimaxH3Ultra,
@@ -805,6 +817,8 @@ impl InferenceModelType {
CommonModelType::Kling3p0Standard => Self::Kling3p0Standard,
CommonModelType::Kling3p0Pro => Self::Kling3p0Pro,
CommonModelType::HappyHorse1p0 => Self::HappyHorse1p0,
CommonModelType::Wan3p0 => Self::Wan3p0,
CommonModelType::Wan3p0Prime => Self::Wan3p0Prime,
CommonModelType::MinimaxH3 => Self::MinimaxH3,
CommonModelType::MinimaxH3Turbo => Self::MinimaxH3Turbo,
CommonModelType::MinimaxH3Ultra => Self::MinimaxH3Ultra,
@@ -954,6 +968,8 @@ mod tests {
assert_serialization(InferenceModelType::Kling3p0Standard, "kling_3p0_standard");
assert_serialization(InferenceModelType::Kling3p0Pro, "kling_3p0_pro");
assert_serialization(InferenceModelType::HappyHorse1p0, "happy_horse_1p0");
assert_serialization(InferenceModelType::Wan3p0, "wan_3p0");
assert_serialization(InferenceModelType::Wan3p0Prime, "wan_3p0_prime");
assert_serialization(InferenceModelType::MinimaxH3, "minimax_h3");
assert_serialization(InferenceModelType::MinimaxH3Turbo, "minimax_h3_turbo");
assert_serialization(InferenceModelType::MinimaxH3Ultra, "minimax_h3_ultra");
@@ -1090,6 +1106,8 @@ mod tests {
assert_eq!(InferenceModelType::Kling3p0Standard.to_str(), "kling_3p0_standard");
assert_eq!(InferenceModelType::Kling3p0Pro.to_str(), "kling_3p0_pro");
assert_eq!(InferenceModelType::HappyHorse1p0.to_str(), "happy_horse_1p0");
assert_eq!(InferenceModelType::Wan3p0.to_str(), "wan_3p0");
assert_eq!(InferenceModelType::Wan3p0Prime.to_str(), "wan_3p0_prime");
assert_eq!(InferenceModelType::MinimaxH3.to_str(), "minimax_h3");
assert_eq!(InferenceModelType::MinimaxH3Turbo.to_str(), "minimax_h3_turbo");
assert_eq!(InferenceModelType::MinimaxH3Ultra.to_str(), "minimax_h3_ultra");
@@ -1228,6 +1246,8 @@ mod tests {
assert_eq!(InferenceModelType::from_str("kling_3p0_standard").unwrap(), InferenceModelType::Kling3p0Standard);
assert_eq!(InferenceModelType::from_str("kling_3p0_pro").unwrap(), InferenceModelType::Kling3p0Pro);
assert_eq!(InferenceModelType::from_str("happy_horse_1p0").unwrap(), InferenceModelType::HappyHorse1p0);
assert_eq!(InferenceModelType::from_str("wan_3p0").unwrap(), InferenceModelType::Wan3p0);
assert_eq!(InferenceModelType::from_str("wan_3p0_prime").unwrap(), InferenceModelType::Wan3p0Prime);
assert_eq!(InferenceModelType::from_str("minimax_h3").unwrap(), InferenceModelType::MinimaxH3);
assert_eq!(InferenceModelType::from_str("minimax_h3_turbo").unwrap(), InferenceModelType::MinimaxH3Turbo);
assert_eq!(InferenceModelType::from_str("minimax_h3_ultra").unwrap(), InferenceModelType::MinimaxH3Ultra);
@@ -163,6 +163,12 @@ pub enum CommonModelType {
Kling3p0Pro,
#[serde(rename = "happy_horse_1p0")]
HappyHorse1p0,
#[serde(rename = "wan_3p0")]
Wan3p0,
#[serde(rename = "wan_3p0_prime")]
Wan3p0Prime,
#[serde(rename = "minimax_h3")]
MinimaxH3,
#[serde(rename = "minimax_h3_turbo")]
@@ -349,6 +355,8 @@ impl CommonModelType {
Self::Kling3p0Standard => "kling_3p0_standard",
Self::Kling3p0Pro => "kling_3p0_pro",
Self::HappyHorse1p0 => "happy_horse_1p0",
Self::Wan3p0 => "wan_3p0",
Self::Wan3p0Prime => "wan_3p0_prime",
Self::MinimaxH3 => "minimax_h3",
Self::MinimaxH3Turbo => "minimax_h3_turbo",
Self::MinimaxH3Ultra => "minimax_h3_ultra",
@@ -472,6 +480,8 @@ impl CommonModelType {
"kling_3p0_standard" => Ok(Self::Kling3p0Standard),
"kling_3p0_pro" => Ok(Self::Kling3p0Pro),
"happy_horse_1p0" => Ok(Self::HappyHorse1p0),
"wan_3p0" => Ok(Self::Wan3p0),
"wan_3p0_prime" => Ok(Self::Wan3p0Prime),
"minimax_h3" => Ok(Self::MinimaxH3),
"minimax_h3_turbo" => Ok(Self::MinimaxH3Turbo),
"minimax_h3_ultra" => Ok(Self::MinimaxH3Ultra),
@@ -599,6 +609,8 @@ impl CommonModelType {
Self::Kling3p0Standard,
Self::Kling3p0Pro,
Self::HappyHorse1p0,
Self::Wan3p0,
Self::Wan3p0Prime,
Self::MinimaxH3,
Self::MinimaxH3Turbo,
Self::MinimaxH3Ultra,
@@ -723,6 +735,8 @@ impl CommonModelType {
Self::Kling3p0Standard => CommonModelClass::Video,
Self::Kling3p0Pro => CommonModelClass::Video,
Self::HappyHorse1p0 => CommonModelClass::Video,
Self::Wan3p0 => CommonModelClass::Video,
Self::Wan3p0Prime => CommonModelClass::Video,
Self::MinimaxH3 => CommonModelClass::Video,
Self::MinimaxH3Turbo => CommonModelClass::Video,
Self::MinimaxH3Ultra => CommonModelClass::Video,
@@ -856,6 +870,8 @@ mod tests {
assert_serialization(CommonModelType::Kling3p0Standard, "kling_3p0_standard");
assert_serialization(CommonModelType::Kling3p0Pro, "kling_3p0_pro");
assert_serialization(CommonModelType::HappyHorse1p0, "happy_horse_1p0");
assert_serialization(CommonModelType::Wan3p0, "wan_3p0");
assert_serialization(CommonModelType::Wan3p0Prime, "wan_3p0_prime");
assert_serialization(CommonModelType::MinimaxH3, "minimax_h3");
assert_serialization(CommonModelType::MinimaxH3Turbo, "minimax_h3_turbo");
assert_serialization(CommonModelType::MinimaxH3Ultra, "minimax_h3_ultra");
@@ -974,6 +990,8 @@ mod tests {
assert_eq!(CommonModelType::Kling3p0Standard.to_str(), "kling_3p0_standard");
assert_eq!(CommonModelType::Kling3p0Pro.to_str(), "kling_3p0_pro");
assert_eq!(CommonModelType::HappyHorse1p0.to_str(), "happy_horse_1p0");
assert_eq!(CommonModelType::Wan3p0.to_str(), "wan_3p0");
assert_eq!(CommonModelType::Wan3p0Prime.to_str(), "wan_3p0_prime");
assert_eq!(CommonModelType::MinimaxH3.to_str(), "minimax_h3");
assert_eq!(CommonModelType::MinimaxH3Turbo.to_str(), "minimax_h3_turbo");
assert_eq!(CommonModelType::MinimaxH3Ultra.to_str(), "minimax_h3_ultra");
@@ -1094,6 +1112,8 @@ mod tests {
assert_eq!(CommonModelType::from_str("kling_3p0_standard").unwrap(), CommonModelType::Kling3p0Standard);
assert_eq!(CommonModelType::from_str("kling_3p0_pro").unwrap(), CommonModelType::Kling3p0Pro);
assert_eq!(CommonModelType::from_str("happy_horse_1p0").unwrap(), CommonModelType::HappyHorse1p0);
assert_eq!(CommonModelType::from_str("wan_3p0").unwrap(), CommonModelType::Wan3p0);
assert_eq!(CommonModelType::from_str("wan_3p0_prime").unwrap(), CommonModelType::Wan3p0Prime);
assert_eq!(CommonModelType::from_str("minimax_h3").unwrap(), CommonModelType::MinimaxH3);
assert_eq!(CommonModelType::from_str("minimax_h3_turbo").unwrap(), CommonModelType::MinimaxH3Turbo);
assert_eq!(CommonModelType::from_str("minimax_h3_ultra").unwrap(), CommonModelType::MinimaxH3Ultra);
@@ -1158,7 +1178,7 @@ mod tests {
#[test]
fn all_variants() {
let mut variants = CommonModelType::all_variants();
assert_eq!(variants.len(), 108);
assert_eq!(variants.len(), 110);
// Image models
assert_eq!(variants.pop_first(), Some(CommonModelType::Flux1Dev));
assert_eq!(variants.pop_first(), Some(CommonModelType::Flux1Schnell));
@@ -1214,6 +1234,8 @@ mod tests {
assert_eq!(variants.pop_first(), Some(CommonModelType::Kling3p0Standard));
assert_eq!(variants.pop_first(), Some(CommonModelType::Kling3p0Pro));
assert_eq!(variants.pop_first(), Some(CommonModelType::HappyHorse1p0));
assert_eq!(variants.pop_first(), Some(CommonModelType::Wan3p0));
assert_eq!(variants.pop_first(), Some(CommonModelType::Wan3p0Prime));
assert_eq!(variants.pop_first(), Some(CommonModelType::MinimaxH3));
assert_eq!(variants.pop_first(), Some(CommonModelType::MinimaxH3Turbo));
assert_eq!(variants.pop_first(), Some(CommonModelType::MinimaxH3Ultra));
@@ -13,11 +13,22 @@ pub const MAX_LENGTH: usize = 16;
/// Common quality levels for generation.
///
/// Declared from "let the model decide" through the highest tier down to the lowest, so the
/// derived `Ord` (and `all_variants()`) reads top-down. Not every model supports every tier;
/// the router clamps unsupported tiers to the nearest one the model offers.
///
/// NB: Keep the max serialized length to 16 characters.
#[cfg_attr(test, derive(EnumIter, EnumCount))]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CommonQuality {
/// Let the model choose. Models without a native "auto" treat this as their default tier.
Auto,
/// Highest tier (GPT Image 2.5 `max`).
Max,
/// Between High and Max (GPT Image 2.5 `xhigh`).
#[serde(rename = "xhigh")]
XHigh,
High,
Medium,
Low,
@@ -30,6 +41,9 @@ impl_mysql_from_row!(CommonQuality);
impl CommonQuality {
pub fn to_str(&self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Max => "max",
Self::XHigh => "xhigh",
Self::High => "high",
Self::Medium => "medium",
Self::Low => "low",
@@ -38,6 +52,9 @@ impl CommonQuality {
pub fn from_str(value: &str) -> Result<Self, EnumError> {
match value {
"auto" => Ok(Self::Auto),
"max" => Ok(Self::Max),
"xhigh" => Ok(Self::XHigh),
"high" => Ok(Self::High),
"medium" => Ok(Self::Medium),
"low" => Ok(Self::Low),
@@ -47,6 +64,9 @@ impl CommonQuality {
pub fn all_variants() -> BTreeSet<Self> {
BTreeSet::from([
Self::Auto,
Self::Max,
Self::XHigh,
Self::High,
Self::Medium,
Self::Low,
@@ -66,6 +86,9 @@ mod tests {
#[test]
fn test_serialization() {
assert_serialization(CommonQuality::Auto, "auto");
assert_serialization(CommonQuality::Max, "max");
assert_serialization(CommonQuality::XHigh, "xhigh");
assert_serialization(CommonQuality::High, "high");
assert_serialization(CommonQuality::Medium, "medium");
assert_serialization(CommonQuality::Low, "low");
@@ -73,6 +96,9 @@ mod tests {
#[test]
fn to_str() {
assert_eq!(CommonQuality::Auto.to_str(), "auto");
assert_eq!(CommonQuality::Max.to_str(), "max");
assert_eq!(CommonQuality::XHigh.to_str(), "xhigh");
assert_eq!(CommonQuality::High.to_str(), "high");
assert_eq!(CommonQuality::Medium.to_str(), "medium");
assert_eq!(CommonQuality::Low.to_str(), "low");
@@ -80,6 +106,9 @@ mod tests {
#[test]
fn from_str() {
assert_eq!(CommonQuality::from_str("auto").unwrap(), CommonQuality::Auto);
assert_eq!(CommonQuality::from_str("max").unwrap(), CommonQuality::Max);
assert_eq!(CommonQuality::from_str("xhigh").unwrap(), CommonQuality::XHigh);
assert_eq!(CommonQuality::from_str("high").unwrap(), CommonQuality::High);
assert_eq!(CommonQuality::from_str("medium").unwrap(), CommonQuality::Medium);
assert_eq!(CommonQuality::from_str("low").unwrap(), CommonQuality::Low);
@@ -99,7 +128,10 @@ mod tests {
#[test]
fn all_variants() {
let mut variants = CommonQuality::all_variants();
assert_eq!(variants.len(), 3);
assert_eq!(variants.len(), 6);
assert_eq!(variants.pop_first(), Some(CommonQuality::Auto));
assert_eq!(variants.pop_first(), Some(CommonQuality::Max));
assert_eq!(variants.pop_first(), Some(CommonQuality::XHigh));
assert_eq!(variants.pop_first(), Some(CommonQuality::High));
assert_eq!(variants.pop_first(), Some(CommonQuality::Medium));
assert_eq!(variants.pop_first(), Some(CommonQuality::Low));
@@ -51,6 +51,12 @@ pub enum CommonVideoModel {
#[serde(rename = "happy_horse_1p0")]
HappyHorse1p0,
#[serde(rename = "wan_3p0")]
Wan3p0,
#[serde(rename = "wan_3p0_prime")]
Wan3p0Prime,
#[serde(rename = "minimax_h3")]
MinimaxH3,
@@ -168,6 +174,8 @@ impl CommonVideoModel {
Self::Kling3p0Standard => CommonModelType::Kling3p0Standard,
Self::Kling3p0Pro => CommonModelType::Kling3p0Pro,
Self::HappyHorse1p0 => CommonModelType::HappyHorse1p0,
Self::Wan3p0 => CommonModelType::Wan3p0,
Self::Wan3p0Prime => CommonModelType::Wan3p0Prime,
Self::MinimaxH3 => CommonModelType::MinimaxH3,
Self::MinimaxH3Turbo => CommonModelType::MinimaxH3Turbo,
Self::MinimaxH3Ultra => CommonModelType::MinimaxH3Ultra,
@@ -224,6 +232,8 @@ mod tests {
assert_serialization(CommonVideoModel::Kling3p0Standard, "kling_3p0_standard");
assert_serialization(CommonVideoModel::Kling3p0Pro, "kling_3p0_pro");
assert_serialization(CommonVideoModel::HappyHorse1p0, "happy_horse_1p0");
assert_serialization(CommonVideoModel::Wan3p0, "wan_3p0");
assert_serialization(CommonVideoModel::Wan3p0Prime, "wan_3p0_prime");
assert_serialization(CommonVideoModel::MinimaxH3, "minimax_h3");
assert_serialization(CommonVideoModel::MinimaxH3Turbo, "minimax_h3_turbo");
assert_serialization(CommonVideoModel::MinimaxH3Ultra, "minimax_h3_ultra");
@@ -273,6 +283,8 @@ mod tests {
("kling_3p0_standard", CommonVideoModel::Kling3p0Standard),
("kling_3p0_pro", CommonVideoModel::Kling3p0Pro),
("happy_horse_1p0", CommonVideoModel::HappyHorse1p0),
("wan_3p0", CommonVideoModel::Wan3p0),
("wan_3p0_prime", CommonVideoModel::Wan3p0Prime),
("minimax_h3", CommonVideoModel::MinimaxH3),
("minimax_h3_turbo", CommonVideoModel::MinimaxH3Turbo),
("minimax_h3_ultra", CommonVideoModel::MinimaxH3Ultra),
@@ -329,6 +341,8 @@ mod tests {
CommonVideoModel::Kling3p0Standard,
CommonVideoModel::Kling3p0Pro,
CommonVideoModel::HappyHorse1p0,
CommonVideoModel::Wan3p0,
CommonVideoModel::Wan3p0Prime,
CommonVideoModel::MinimaxH3,
CommonVideoModel::MinimaxH3Turbo,
CommonVideoModel::MinimaxH3Ultra,
@@ -384,6 +398,8 @@ mod tests {
(CommonVideoModel::Kling3p0Standard, CommonModelType::Kling3p0Standard),
(CommonVideoModel::Kling3p0Pro, CommonModelType::Kling3p0Pro),
(CommonVideoModel::HappyHorse1p0, CommonModelType::HappyHorse1p0),
(CommonVideoModel::Wan3p0, CommonModelType::Wan3p0),
(CommonVideoModel::Wan3p0Prime, CommonModelType::Wan3p0Prime),
(CommonVideoModel::MinimaxH3, CommonModelType::MinimaxH3),
(CommonVideoModel::MinimaxH3Turbo, CommonModelType::MinimaxH3Turbo),
(CommonVideoModel::MinimaxH3Ultra, CommonModelType::MinimaxH3Ultra),
@@ -0,0 +1,162 @@
use std::collections::BTreeSet;
#[cfg(test)]
use strum::EnumCount;
#[cfg(test)]
use strum::EnumIter;
use utoipa::ToSchema;
use crate::error::enum_error::EnumError;
/// Maximum serialized string length for database storage.
pub const MAX_LENGTH: usize = 16;
/// Output video containers for generation. Unset options retain the provider default.
/// Models without output-format support ignore this option.
///
/// NB: Keep the max serialized length to 16 characters.
#[cfg_attr(test, derive(EnumIter, EnumCount))]
#[derive(Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum CommonVideoOutputFormat {
#[serde(rename = "mp4")]
Mp4,
#[serde(rename = "mov")]
Mov,
}
impl_enum_display_and_debug_using_to_str!(CommonVideoOutputFormat);
impl_mysql_enum_coders!(CommonVideoOutputFormat);
impl_mysql_from_row!(CommonVideoOutputFormat);
impl CommonVideoOutputFormat {
pub fn to_str(&self) -> &'static str {
match self {
Self::Mp4 => "mp4",
Self::Mov => "mov",
}
}
pub fn from_str(value: &str) -> Result<Self, EnumError> {
match value {
"mp4" => Ok(Self::Mp4),
"mov" => Ok(Self::Mov),
_ => Err(EnumError::CouldNotConvertFromString(value.to_string())),
}
}
pub fn all_variants() -> BTreeSet<Self> {
BTreeSet::from([
Self::Mp4,
Self::Mov,
])
}
}
#[cfg(test)]
mod tests {
use crate::common::generation::common_video_output_format::CommonVideoOutputFormat;
use crate::common::generation::common_video_output_format::MAX_LENGTH;
use crate::test_helpers::assert_serialization;
mod explicit_checks {
use super::*;
use crate::error::enum_error::EnumError;
#[test]
fn test_serialization() {
assert_serialization(CommonVideoOutputFormat::Mp4, "mp4");
assert_serialization(CommonVideoOutputFormat::Mov, "mov");
}
#[test]
fn to_str() {
assert_eq!(CommonVideoOutputFormat::Mp4.to_str(), "mp4");
assert_eq!(CommonVideoOutputFormat::Mov.to_str(), "mov");
}
#[test]
fn from_str() {
assert_eq!(CommonVideoOutputFormat::from_str("mp4").unwrap(), CommonVideoOutputFormat::Mp4);
assert_eq!(CommonVideoOutputFormat::from_str("mov").unwrap(), CommonVideoOutputFormat::Mov);
}
#[test]
fn from_str_err() {
let result = CommonVideoOutputFormat::from_str("invalid");
assert!(result.is_err());
if let Err(EnumError::CouldNotConvertFromString(value)) = result {
assert_eq!(value, "invalid");
} else {
panic!("Expected EnumError::CouldNotConvertFromString");
}
}
#[test]
fn all_variants() {
let mut variants = CommonVideoOutputFormat::all_variants();
assert_eq!(variants.len(), 2);
assert_eq!(variants.pop_first(), Some(CommonVideoOutputFormat::Mp4));
assert_eq!(variants.pop_first(), Some(CommonVideoOutputFormat::Mov));
assert_eq!(variants.pop_first(), None);
}
}
mod mechanical_checks {
use super::*;
#[test]
fn variant_length() {
use strum::IntoEnumIterator;
assert_eq!(CommonVideoOutputFormat::all_variants().len(), CommonVideoOutputFormat::iter().len());
}
#[test]
fn round_trip() {
for variant in CommonVideoOutputFormat::all_variants() {
assert_eq!(variant, CommonVideoOutputFormat::from_str(variant.to_str()).unwrap());
assert_eq!(variant, CommonVideoOutputFormat::from_str(&format!("{}", variant)).unwrap());
assert_eq!(variant, CommonVideoOutputFormat::from_str(&format!("{:?}", variant)).unwrap());
}
}
#[test]
fn serialized_length_ok_for_database() {
for variant in CommonVideoOutputFormat::all_variants() {
let serialized = variant.to_str();
assert!(serialized.len() > 0, "variant {:?} is too short", variant);
assert!(serialized.len() <= MAX_LENGTH, "variant {:?} is too long via to_str()", variant);
}
for variant in CommonVideoOutputFormat::all_variants() {
let json = serde_json::to_string(&variant).unwrap().replace('"', "");
assert!(json.len() <= MAX_LENGTH, "variant {:?} is too long via JSON: {:?}", variant, json);
}
}
#[test]
fn serialized_names_must_not_contain_dots() {
for variant in CommonVideoOutputFormat::all_variants() {
let to_str_value = variant.to_str();
assert!(!to_str_value.contains('.'), "to_str() for {:?} contains a dot: {:?}", variant, to_str_value);
let json_value = serde_json::to_string(&variant).unwrap().replace('"', "");
assert!(!json_value.contains('.'), "JSON serialization for {:?} contains a dot: {:?}", variant, json_value);
}
}
#[test]
fn serialized_names_must_only_contain_lowercase_alphanumeric_and_underscore() {
let valid_pattern = regex::Regex::new(r"^[a-z0-9_]+$").unwrap();
for variant in CommonVideoOutputFormat::all_variants() {
let to_str_value = variant.to_str();
assert!(valid_pattern.is_match(to_str_value),
"to_str() for {:?} contains invalid characters: {:?} (only a-z, 0-9, _ allowed)", variant, to_str_value);
let json_value = serde_json::to_string(&variant).unwrap().replace('"', "");
assert!(valid_pattern.is_match(&json_value),
"JSON serialization for {:?} contains invalid characters: {:?} (only a-z, 0-9, _ allowed)", variant, json_value);
}
}
}
}
@@ -15,3 +15,4 @@ pub mod model_creator;
pub mod common_resolution;
pub mod common_splat_model;
pub mod common_video_model;
pub mod common_video_output_format;
@@ -12,12 +12,19 @@ export enum CommonImageModel {
GptImage2 = "gpt_image_2",
GptImage2p5Flare = "gpt_image_2p5_flare",
GptImage2p5Sunburst = "gpt_image_2p5_sunburst",
GrokImagineImage = "grok_imagine_image",
GrokImagineImageQuality = "grok_imagine_image_q",
Midjourney7 = "midjourney_7",
Midjourney7Niji = "midjourney_7_niji",
Midjourney8 = "midjourney_8",
NanaBanana = "nano_banana",
NanaBanana2 = "nano_banana_2",
NanaBananaPro = "nano_banana_pro",
Seedream4 = "seedream_4",
Seedream4p5 = "seedream_4p5",
Seedream5Lite = "seedream_5_lite",
Seedream5p0Pro = "seedream_5p0_pro",
Seedream5p0ProUltra = "seedream_5p0_pro_u",
QwenEdit2511Angles = "qwen_edit_2511_angles",
Flux2LoraAngles = "flux_2_lora_angles",
}
@@ -3,6 +3,9 @@
// In the future, we should use code gen (protobufs or similar) to keep the two sides in sync.
export enum CommonQuality {
Auto = "auto",
Max = "max",
XHigh = "xhigh",
High = "high",
Medium = "medium",
Low = "low",
@@ -4,6 +4,10 @@
export enum CommonVideoModel {
GrokVideo = "grok_video",
GrokImagineVideo = "grok_imagine_video",
GrokImagineVideo1p5 = "grok_imagine_video_1p5",
Flux3 = "flux_3",
Flux3Draft = "flux_3_draft",
Kling16Pro = "kling_1p6_pro",
Kling21Pro = "kling_2p1_pro",
Kling21Master = "kling_2p1_master",
@@ -11,10 +15,28 @@ export enum CommonVideoModel {
Kling2p6Pro = "kling_2p6_pro",
Kling3p0Standard = "kling_3p0_standard",
Kling3p0Pro = "kling_3p0_pro",
HappyHorse1p0 = "happy_horse_1p0",
Wan3p0 = "wan_3p0",
Wan3p0Prime = "wan_3p0_prime",
MinimaxH3 = "minimax_h3",
MinimaxH3Turbo = "minimax_h3_turbo",
MinimaxH3Ultra = "minimax_h3_ultra",
Seedance10Lite = "seedance_1p0_lite",
Seedance1p5Pro = "seedance_1p5_pro",
Seedance2p0 = "seedance_2p0",
Seedance2p0Fast = "seedance_2p0_fast",
Seedance2p0BytePlus = "seedance_2p0_bp",
Seedance2p0BytePlusFast = "seedance_2p0_bp_fast",
Seedance2p0Ultra = "seedance_2p0_u",
Seedance2p0UltraFast = "seedance_2p0_u_fast",
Seedance2p0BytePlusUltra = "seedance_2p0_bpu",
Seedance2p0BytePlusUltraFast = "seedance_2p0_bpu_fast",
Seedance2p0Mini = "seedance_2p0_mini",
Seedance2p0BytePlusMini = "seedance_2p0_bp_mini",
Seedance2p0BytePlusUltraMini = "seedance_2p0_bpu_mini",
Seedance2p5Preview = "seedance_2p5_preview",
Seedance2p5 = "seedance_2p5",
Seedance2p5Ultra = "seedance_2p5_u",
Sora2 = "sora_2",
Sora2Pro = "sora_2_pro",
Veo2 = "veo_2",
@@ -22,4 +44,9 @@ export enum CommonVideoModel {
Veo3Fast = "veo_3_fast",
Veo3p1 = "veo_3p1",
Veo3p1Fast = "veo_3p1_fast",
Veo3p1Lite = "veo_3p1_lite",
ViduQ3 = "vidu_q3",
ViduQ3Turbo = "vidu_q3_turbo",
PreviewModel = "preview_model",
PreviewModelFast = "preview_model_fast",
}
@@ -0,0 +1,167 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DesktopLoginBridge } from "./DesktopLoginBridge";
const { native, forbiddenFetch } = vi.hoisted(() => ({ native: vi.fn(), forbiddenFetch: vi.fn(() => { throw new Error("JavaScript must never call HTTP for login"); }) }));
vi.mock("@tauri-apps/api/core", () => ({ invoke: native }));
vi.mock("@storyteller/tauri-utils", () => ({ FetchProxy: forbiddenFetch }));
vi.mock("@storyteller/api", () => { throw new Error("Login UI must only import API types"); });
vi.mock("qrcode.react", () => ({ QRCodeSVG: ({ value }: { value: string }) => <svg role="img" aria-label="Login QR" data-value={value} /> }));
const CHALLENGE_ID = "local-handle";
const APPROVAL_URL = `https://app.getartcraft.com/login/desktop#approval_token=${"A".repeat(43)}`;
const USER = { user_token: "user_fixture", username: "google_user" };
let outcome: Record<string, unknown>;
let expiresIn: number;
beforeEach(() => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-09-25T12:00:00Z"));
vi.stubGlobal("fetch", forbiddenFetch);
localStorage.clear();
native.mockReset();
forbiddenFetch.mockClear();
expiresIn = 1_200_000;
outcome = { status: "pending", maybe_failure_type: null, maybe_user: null };
native.mockImplementation(async (command: string) => {
if (command === "storyteller_create_login_challenge_command") return {
challenge_id: CHALLENGE_ID, verification_url: APPROVAL_URL,
confirmation_code: "WDJBMJHT", expires_at: new Date(Date.now() + expiresIn).toISOString(), poll_interval_seconds: 5,
};
if (command === "storyteller_poll_login_challenge_command") return outcome;
if (command === "storyteller_cancel_login_challenge_command" || command === "plugin:opener|open_url") return;
throw new Error(`Unexpected native command: ${command}`);
});
});
afterEach(() => {
cleanup();
expect(forbiddenFetch).not.toHaveBeenCalled();
expect(localStorage.getItem("artcraft_signed_session")).toBeNull();
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe("desktop native login bridge integration", () => {
it("creates through IPC and opens the native browser with the matching QR/code", async () => {
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Login with Website");
expect(native).toHaveBeenCalledWith("storyteller_create_login_challenge_command");
expect(native).toHaveBeenCalledWith("plugin:opener|open_url", { url: APPROVAL_URL });
expect(screen.getByRole("img", { name: "Login QR" }).getAttribute("data-value")).toBe(APPROVAL_URL);
expect(screen.getByText("WDJB-MJHT")).toBeTruthy();
});
it("polls with only a local handle and accepts the natively verified user without seeing credentials", async () => {
const success = vi.fn();
render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
await tick(5000);
expect(success).not.toHaveBeenCalled();
outcome = { status: "redeemed", maybe_failure_type: null, maybe_user: USER };
await tick(5000);
expect(native).toHaveBeenCalledWith("storyteller_poll_login_challenge_command", { challengeId: CHALLENGE_ID });
expect(success).toHaveBeenCalledWith(USER);
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: CHALLENGE_ID });
const count = calls("storyteller_poll_login_challenge_command");
await tick(30_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(count);
});
it("stops after decline", async () => {
const success = vi.fn();
outcome = { status: "failed", maybe_failure_type: "user_declined" };
render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
await tick(5000);
expect(screen.getByText("Login was declined on the website.")).toBeTruthy();
expect(success).not.toHaveBeenCalled();
await tick(60_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
});
it("expires locally and cancels the native attempt without creating another", async () => {
expiresIn = 5000;
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
await tick(5000);
expect(screen.getByText("Login request expired. Start a new request.")).toBeTruthy();
expect(calls("storyteller_create_login_challenge_command")).toBe(1);
expect(calls("storyteller_poll_login_challenge_command")).toBe(0);
expect(calls("storyteller_cancel_login_challenge_command")).toBe(1);
});
it("backs off a native network failure and retries the same local handle", async () => {
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
native.mockRejectedValueOnce({ message: "Disconnected", status: null, retryable: true });
await tick(5000);
expect(screen.getByText("Connection interrupted. Retrying…")).toBeTruthy();
await tick(9999);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
await tick(1);
expect(calls("storyteller_poll_login_challenge_command")).toBe(2);
});
it("cancels on unmount and ignores a late command result", async () => {
let resolve: (value: unknown) => void = () => {};
const success = vi.fn();
const view = render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
native.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
await tick(5000);
view.unmount();
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: CHALLENGE_ID });
await act(async () => { resolve({ status: "redeemed", maybe_user: USER }); });
expect(success).not.toHaveBeenCalled();
});
it("ignores an in-flight redemption after Back and can start a new challenge", async () => {
let resolve: (value: unknown) => void = () => {};
const success = vi.fn();
render(<DesktopLoginBridge onSuccess={success} />);
await start("Scan to Login");
native.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
await tick(5000);
await start("Back");
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: CHALLENGE_ID });
await act(async () => { resolve({ status: "redeemed", maybe_user: USER }); });
expect(success).not.toHaveBeenCalled();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
await tick(30_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
await start("Scan to Login");
expect(screen.getByRole("img", { name: "Login QR" })).toBeTruthy();
outcome = { status: "redeemed", maybe_user: USER };
await tick(5000);
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
});
it("fails closed on a future status", async () => {
outcome = { status: "future_state", maybe_user: USER };
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
await tick(5000);
expect(screen.getByText("This login request could not be completed. Start a new request.")).toBeTruthy();
});
it("shows the native host/status diagnostic and stops on terminal HTTP errors", async () => {
render(<DesktopLoginBridge onSuccess={vi.fn()} />);
await start("Scan to Login");
native.mockRejectedValueOnce({ message: "http://localhost:12345: Login server rejected the request (HTTP 401)", status: 401, retryable: false });
await tick(5000);
expect(screen.getByText(/localhost:12345.*401/)).toBeTruthy();
await tick(60_000);
expect(calls("storyteller_poll_login_challenge_command")).toBe(1);
});
});
async function start(label: string) {
await act(async () => { fireEvent.click(screen.getByRole("button", { name: label })); });
}
async function tick(ms: number) {
await act(async () => { await vi.advanceTimersByTimeAsync(ms); });
}
function calls(command: string) {
return native.mock.calls.filter(([name]) => name === command).length;
}
@@ -0,0 +1,134 @@
import { useEffect, useRef, useState } from "react";
import { QRCodeSVG } from "qrcode.react";
import { invoke } from "@tauri-apps/api/core";
import { ArrowLeftIcon } from "lucide-react";
import type { UserInfo } from "@storyteller/api";
import { createDesktopLoginChallenge, pollDesktopLoginChallenge, cancelDesktopLoginChallenge, isDesktopLoginError, type DesktopLoginChallenge } from "./NativeLoginBridge";
const OpenUrl = (url: string) => invoke("plugin:opener|open_url", { url });
export function DesktopLoginBridge({ onSuccess, onStart, onActiveChange }: { onSuccess: (user: UserInfo) => void; onStart?: () => void; onActiveChange?: (active: boolean) => void }) {
const [challenge, setChallenge] = useState<DesktopLoginChallenge | null>(null);
const [busy, setBusy] = useState(false);
const [message, setMessage] = useState("");
const [now, setNow] = useState(Date.now);
const generation = useRef(0);
const success = useRef(onSuccess);
success.current = onSuccess;
const isActive = busy || challenge !== null;
useEffect(() => { onActiveChange?.(isActive); }, [isActive, onActiveChange]);
useEffect(() => () => { generation.current += 1; }, []);
useEffect(() => {
if (!challenge) return;
const timer = window.setInterval(() => setNow(Date.now()), 1000);
return () => window.clearInterval(timer);
}, [challenge]);
useEffect(() => {
if (!challenge) return;
let active = true;
const current = generation.current;
let timer: ReturnType<typeof setTimeout>;
let delay = Math.max(5, challenge.poll_interval_seconds) * 1000;
const deadline = Date.parse(challenge.expires_at);
const finish = (text: string) => {
setChallenge(null);
setMessage(text);
};
const poll = async () => {
if (!active || current !== generation.current) return;
if (Date.now() >= deadline) { finish("Login request expired. Start a new request."); return; }
try {
const result = await pollDesktopLoginChallenge(challenge.challenge_id);
if (!active || current !== generation.current) return;
if (result.status === "redeemed") {
if (!result.maybe_user) throw new Error("Native session verification did not return a user");
active = false;
setChallenge(null);
setMessage("Signed in successfully.");
success.current(result.maybe_user);
return;
}
if (result.status === "failed") {
finish(result.maybe_failure_type === "user_declined" ? "Login was declined on the website." : result.maybe_failure_type === "expired" ? "Login request expired. Start a new request." : "Login failed. Start a new request.");
return;
}
if (!["pending", "approved"].includes(result.status)) {
finish("This login request could not be completed. Start a new request.");
return;
}
delay = Math.max(5, challenge.poll_interval_seconds) * 1000;
setMessage("Waiting for your confirmation on the website…");
} catch (error) {
if (!active || current !== generation.current) return;
if (isDesktopLoginError(error) && !error.retryable) {
finish(error.message);
return;
}
delay = Math.min(delay * 2, 30_000);
setMessage("Connection interrupted. Retrying…");
}
if (active) timer = setTimeout(poll, Math.min(delay, Math.max(0, deadline - Date.now())));
};
timer = setTimeout(poll, Math.min(delay, Math.max(0, deadline - Date.now())));
return () => {
active = false;
clearTimeout(timer);
void cancelDesktopLoginChallenge(challenge.challenge_id).catch(() => {});
};
}, [challenge]);
const start = async (openBrowser: boolean) => {
if (busy) return;
onStart?.();
const current = ++generation.current;
setBusy(true);
setMessage("");
try {
const created = await createDesktopLoginChallenge();
if (current !== generation.current) {
void cancelDesktopLoginChallenge(created.challenge_id).catch(() => {});
return;
}
// Rust validates the approval URL against the configured API environment.
setNow(Date.now());
setChallenge(created);
setMessage("Waiting for your confirmation on the website…");
if (openBrowser) await OpenUrl(created.verification_url);
} catch (error) {
if (current === generation.current) setMessage(isDesktopLoginError(error) ? error.message : "Unable to open website login. Try again or scan the QR code.");
} finally {
if (current === generation.current) setBusy(false);
}
};
const back = () => {
generation.current += 1;
setChallenge(null);
setBusy(false);
setMessage("");
};
const remaining = challenge ? Math.max(0, Math.ceil((Date.parse(challenge.expires_at) - now) / 1000)) : 0;
return <section aria-label="Website login" className="mb-6 rounded-xl border border-white/15 p-4 text-center">
{isActive && <div className="mb-4 text-left">
<button type="button" className="inline-flex items-center gap-2 text-sm text-white/70 hover:text-white" onClick={back}>
<ArrowLeftIcon size={16} aria-hidden="true" /> Back
</button>
</div>}
{challenge ? <>
<p className="mb-3 text-sm text-white/70">Scan with your phone or approve in your browser.</p>
<QRCodeSVG value={challenge.verification_url} size={192} marginSize={4} title="Scan to approve desktop login" className="mx-auto rounded-lg" />
<p className="my-3 font-mono text-2xl tracking-widest">{challenge.confirmation_code.slice(0, 4)}-{challenge.confirmation_code.slice(4)}</p>
<p className="mb-3 text-xs text-white/60">Verify this code on the website. Expires in {Math.floor(remaining / 60)}:{String(remaining % 60).padStart(2, "0")}</p>
<button type="button" className="rounded-lg border border-white/30 px-4 py-2" onClick={() => OpenUrl(challenge.verification_url).catch(() => setMessage("Unable to open the browser. Scan the QR code instead."))}>Open website</button>
</> : busy ? <p className="text-sm text-white/70" role="status">Preparing login…</p> : <div className="flex flex-col gap-2">
<button type="button" className="rounded-lg bg-white px-4 py-3 font-medium text-black" onClick={() => start(true)}>Login with Website</button>
<button type="button" className="rounded-lg border border-white/30 px-4 py-2" onClick={() => start(false)}>Scan to Login</button>
<p className="text-xs text-white/50">Use Google or any account already signed in on the website.</p>
</div>}
{message && <p className="mt-3 text-sm text-white/70" role="status">{message}</p>}
</section>;
}
@@ -0,0 +1,86 @@
.panel {
position: relative;
isolation: isolate;
display: flex;
width: 100%;
flex-direction: column;
align-items: center;
overflow: hidden;
padding: 56px 32px;
text-align: center;
background: radial-gradient(ellipse at 50% 0%, rgb(94 234 212 / 9%), transparent 70%);
animation: arrive 450ms ease-out both;
}
.glow {
position: absolute;
z-index: -1;
top: -52px;
left: calc(50% - 144px);
width: 288px;
height: 288px;
border-radius: 50%;
background: radial-gradient(circle, rgb(94 234 212 / 24%), rgb(129 140 248 / 12%) 45%, transparent 70%);
filter: blur(24px);
pointer-events: none;
animation: glow 2400ms ease-in-out infinite;
}
.badge {
display: flex;
width: 76px;
height: 76px;
align-items: center;
justify-content: center;
margin-bottom: 28px;
border: 1px solid rgb(153 246 228 / 35%);
border-radius: 50%;
color: #b4f7de;
background: linear-gradient(145deg, rgb(153 246 228 / 16%), rgb(94 234 212 / 4%));
box-shadow: 0 0 0 8px rgb(94 234 212 / 4%), 0 0 44px rgb(94 234 212 / 18%), inset 0 1px 0 rgb(255 255 255 / 12%);
}
.heading {
margin: 0;
max-width: 100%;
color: rgb(255 255 255 / 80%);
font-size: 18px;
font-weight: 500;
line-height: 1.5;
}
.username {
display: block;
margin-top: 4px;
overflow-wrap: anywhere;
color: #b4f7de;
background: linear-gradient(100deg, #d4ffec, #99f6e4 55%, #c7d2fe);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 30px;
font-weight: 600;
letter-spacing: -0.025em;
line-height: 1.25;
}
.caption {
margin: 14px 0 0;
color: rgb(255 255 255 / 50%);
font-size: 14px;
line-height: 1.5;
}
@keyframes arrive {
from { opacity: 0; transform: translateY(8px) scale(0.98); }
to { opacity: 1; transform: translateY(0) scale(1); }
}
@keyframes glow {
0%, 100% { opacity: 0.7; transform: scale(0.95); }
50% { opacity: 1; transform: scale(1.06); }
}
@media (prefers-reduced-motion: reduce) {
.panel, .glow { animation: none; }
}
@@ -0,0 +1,18 @@
import { CheckIcon } from "lucide-react";
import styles from "./LoginSuccess.module.css";
export function LoginSuccess({ username }: { username: string }) {
return (
<div className={styles.panel} role="status" aria-live="polite" aria-atomic="true">
<div className={styles.glow} aria-hidden="true" />
<div className={styles.badge} aria-hidden="true">
<CheckIcon size={34} strokeWidth={2} />
</div>
<h2 className={styles.heading}>
Logged in as{" "}
<span className={styles.username}>{username}</span>
</h2>
<p className={styles.caption}>You're ready to create.</p>
</div>
);
}
@@ -0,0 +1,38 @@
import { invoke } from "@tauri-apps/api/core";
import type { UserInfo } from "@storyteller/api";
export interface DesktopLoginChallenge {
challenge_id: string;
verification_url: string;
confirmation_code: string;
expires_at: string;
poll_interval_seconds: number;
}
export interface DesktopLoginOutcome {
status: string;
maybe_failure_type: string | null;
maybe_user: UserInfo | null;
}
export interface DesktopLoginError {
status: number | null;
message: string;
retryable: boolean;
}
export const createDesktopLoginChallenge = () => invoke<DesktopLoginChallenge>("storyteller_create_login_challenge_command");
export const pollDesktopLoginChallenge = (challengeId: string) => invoke<DesktopLoginOutcome>("storyteller_poll_login_challenge_command", { challengeId });
export const cancelDesktopLoginChallenge = (challengeId: string) => invoke<void>("storyteller_cancel_login_challenge_command", { challengeId });
export function isDesktopLoginError(error: unknown): error is DesktopLoginError {
return typeof error === "object" && error !== null && "message" in error && "retryable" in error;
}
export const getNativeLoginSession = () => invoke<UserInfo | null>("storyteller_get_login_session_command");
export const passwordLogin = (usernameOrEmail: string, password: string) => invoke<UserInfo>("storyteller_password_login_command", {
request: { username_or_email: usernameOrEmail, password },
});
export const passwordSignup = (username: string, email: string, password: string, passwordConfirmation: string) => invoke<UserInfo>("storyteller_password_signup_command", {
request: { username, email_address: email, password, password_confirmation: passwordConfirmation, signup_source: "artcraft" },
});
@@ -1,12 +1,182 @@
import { render } from '@testing-library/react';
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { LoginModal } from "./login-modal";
import { useLoginModalStore } from "./useLoginModalStore";
import LoginModal from './login-modal';
const { native, forbiddenFetch } = vi.hoisted(() => ({ native: vi.fn(), forbiddenFetch: vi.fn(() => { throw new Error("Authentication HTTP must run in Rust"); }) }));
vi.mock("@tauri-apps/api/core", () => ({ invoke: native }));
vi.mock("@storyteller/api", () => { throw new Error("Authentication UI must not import API clients"); });
vi.mock("@storyteller/tauri-utils", () => ({ FetchProxy: forbiddenFetch }));
vi.mock("@headlessui/react", () => ({ Transition: ({ show, children }: any) => show ? children : null, TransitionChild: ({ children }: any) => children }));
vi.mock("@storyteller/icons", () => ({ DynamicIcon: () => null, DiscordIcon: () => null }));
vi.mock("@storyteller/ui-button", () => ({ Button: ({ children, variant, icon, iconFlip, ...props }: any) => <button {...props}>{children}</button> }));
vi.mock("@storyteller/ui-input", () => ({ Input: ({ inputClassName, ...props }: any) => <input {...props} /> }));
vi.mock("qrcode.react", () => ({ QRCodeSVG: () => <svg role="img" aria-label="Login QR" /> }));
describe('LoginModal', () => {
it('should render successfully', () => {
const { baseElement } = render(<LoginModal />);
expect(baseElement).toBeTruthy();
const USER = { username: "google_user", user_token: "u_test" };
beforeEach(() => {
vi.useFakeTimers();
vi.stubGlobal("fetch", forbiddenFetch);
forbiddenFetch.mockClear();
localStorage.clear();
useLoginModalStore.setState({ isOpen: true, recheckTrigger: 0 });
native.mockReset().mockImplementation(async (command: string) => {
if (command === "storyteller_get_login_session_command") return null;
if (command === "storyteller_create_login_challenge_command") return {
challenge_id: "native_handle", verification_url: `https://app.getartcraft.com/login/desktop#approval_token=${"A".repeat(43)}`,
confirmation_code: "WDJBMJHT", expires_at: new Date(Date.now() + 1_200_000).toISOString(), poll_interval_seconds: 5,
};
if (command === "storyteller_poll_login_challenge_command") return { status: "redeemed", maybe_user: USER };
if (command === "storyteller_password_login_command" || command === "storyteller_password_signup_command") return USER;
if (command === "storyteller_cancel_login_challenge_command" || command === "plugin:opener|open_url") return;
throw new Error(`Unexpected command: ${command}`);
});
});
afterEach(() => {
cleanup();
expect(forbiddenFetch).not.toHaveBeenCalled();
expect(localStorage.getItem("artcraft_signed_session")).toBeNull();
vi.unstubAllGlobals();
vi.useRealTimers();
});
describe("native login modal integration", () => {
it("shows website and QR login only on the login screen", async () => {
await act(async () => { render(<LoginModal />); });
expect(screen.getByText("Create your account")).toBeTruthy();
expect(screen.queryByRole("button", { name: "Login with Website" })).toBeNull();
expect(screen.queryByRole("button", { name: "Scan to Login" })).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Log in" }));
expect(screen.getByRole("button", { name: "Login with Website" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Scan to Login" })).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "Sign up" }));
expect(screen.queryByRole("button", { name: "Login with Website" })).toBeNull();
});
it.each(["Login with Website", "Scan to Login"])("hides password login during %s and restores it with Back", async (label) => {
const success = vi.fn();
await act(async () => { render(<LoginModal isSignUp={false} onArtCraftAuthSuccess={success} />); });
expect(screen.getByPlaceholderText("you@example.com or username")).toBeTruthy();
await act(async () => { fireEvent.click(screen.getByRole("button", { name: label })); });
expect(screen.getByRole("img", { name: "Login QR" })).toBeTruthy();
expect(screen.queryByPlaceholderText("you@example.com or username")).toBeNull();
expect(screen.queryByPlaceholderText("Min. 8 characters")).toBeNull();
expect(screen.queryByRole("button", { name: "Sign up" })).toBeNull();
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Back" })); });
expect(screen.getByPlaceholderText("you@example.com or username")).toBeTruthy();
expect(screen.getByPlaceholderText("Min. 8 characters")).toBeTruthy();
expect(screen.getByRole("button", { name: "Login with Website" })).toBeTruthy();
expect(screen.getByRole("button", { name: "Scan to Login" })).toBeTruthy();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: "native_handle" });
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
expect(native.mock.calls.filter(([command]) => command === "storyteller_poll_login_challenge_command")).toHaveLength(0);
expect(success).not.toHaveBeenCalled();
});
it("hides password login while preparing a challenge and cancels a late creation after Back", async () => {
let resolve: (value: unknown) => void = () => {};
await act(async () => { render(<LoginModal isSignUp={false} />); });
native.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Login with Website" })); });
expect(screen.getByText("Preparing login…")).toBeTruthy();
expect(screen.queryByPlaceholderText("Min. 8 characters")).toBeNull();
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Back" })); });
await act(async () => { resolve({ challenge_id: "late_handle" }); });
expect(screen.getByPlaceholderText("Min. 8 characters")).toBeTruthy();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
expect(native).toHaveBeenCalledWith("storyteller_cancel_login_challenge_command", { challengeId: "late_handle" });
expect(native.mock.calls.filter(([command]) => command === "plugin:opener|open_url")).toHaveLength(0);
});
it.each([true, false])("keeps the completed native login when a stale session check resolves (before completion: %s)", async (beforeCompletion) => {
let resolveSession: (value: unknown) => void = () => {};
native.mockImplementationOnce(() => new Promise((resolve) => { resolveSession = resolve; }));
const success = vi.fn();
await act(async () => { render(<LoginModal isSignUp={false} onArtCraftAuthSuccess={success} />); });
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Scan to Login" })); });
if (beforeCompletion) await act(async () => { resolveSession(null); });
expect(screen.getByRole("img", { name: "Login QR" })).toBeTruthy();
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
if (!beforeCompletion) await act(async () => { resolveSession(null); });
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
expect(screen.queryByRole("img", { name: "Login QR" })).toBeNull();
expect(useLoginModalStore.getState().isOpen).toBe(true);
await act(async () => { await vi.advanceTimersByTimeAsync(2999); });
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
expect(useLoginModalStore.getState().isOpen).toBe(false);
expect(screen.queryByRole("heading", { name: "Logged in as google_user" })).toBeNull();
expect(screen.queryByText("Create your account")).toBeNull();
expect(native).toHaveBeenCalledWith("storyteller_poll_login_challenge_command", { challengeId: "native_handle" });
});
it.each([false, true])("submits password authentication only through Rust (signup: %s)", async (signup) => {
const success = vi.fn();
await act(async () => { render(<LoginModal isSignUp={signup} onArtCraftAuthSuccess={success} />); });
if (signup) {
fireEvent.change(screen.getByPlaceholderText("Username"), { target: { value: "native_user" } });
fireEvent.change(screen.getByPlaceholderText("you@example.com"), { target: { value: "user@example.com" } });
fireEvent.change(screen.getByPlaceholderText("Re-enter password"), { target: { value: "password123" } });
} else {
fireEvent.change(screen.getByPlaceholderText("you@example.com or username"), { target: { value: "native_user" } });
}
fireEvent.change(screen.getByPlaceholderText("Min. 8 characters"), { target: { value: "password123" } });
const submit = screen.getAllByRole("button", { name: signup ? "Sign up" : "Log in" }).find((button) => button.getAttribute("type") === "submit")!;
await act(async () => { fireEvent.click(submit); });
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
expect(native).toHaveBeenCalledWith(signup ? "storyteller_password_signup_command" : "storyteller_password_login_command", {
request: signup ? { username: "native_user", email_address: "user@example.com", password: "password123", password_confirmation: "password123", signup_source: "artcraft" } : { username_or_email: "native_user", password: "password123" },
});
if (!signup) {
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
expect(screen.queryByText("Join Our Community")).toBeNull();
await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
expect(useLoginModalStore.getState().isOpen).toBe(false);
}
});
it("dismisses the confirmation once even when callbacks change", async () => {
const firstClose = vi.fn();
const latestClose = vi.fn();
const success = vi.fn();
const view = render(<LoginModal isSignUp={false} onClose={firstClose} onArtCraftAuthSuccess={success} />);
await act(async () => {});
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Login with Website" })); });
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(screen.getByRole("status").textContent).toContain("Logged in as google_user");
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
view.rerender(<LoginModal isSignUp={false} onClose={latestClose} onArtCraftAuthSuccess={success} />);
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
expect(useLoginModalStore.getState().isOpen).toBe(false);
expect(firstClose).not.toHaveBeenCalled();
expect(latestClose).toHaveBeenCalledTimes(1);
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(latestClose).toHaveBeenCalledTimes(1);
});
it("cleans up the confirmation timer on unmount", async () => {
const onClose = vi.fn();
const view = render(<LoginModal isSignUp={false} onClose={onClose} />);
await act(async () => {});
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Scan to Login" })); });
await act(async () => { await vi.advanceTimersByTimeAsync(5000); });
expect(screen.getByRole("heading", { name: "Logged in as google_user" })).toBeTruthy();
view.unmount();
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(onClose).not.toHaveBeenCalled();
});
it("restores an existing session without showing the login confirmation", async () => {
native.mockResolvedValueOnce(USER);
const success = vi.fn();
await act(async () => { render(<LoginModal onArtCraftAuthSuccess={success} />); });
expect(success).toHaveBeenCalledExactlyOnceWith(USER);
expect(useLoginModalStore.getState().isOpen).toBe(false);
expect(screen.queryByRole("heading", { name: "Logged in as google_user" })).toBeNull();
});
});
@@ -1,17 +1,19 @@
import { Button } from "@storyteller/ui-button";
import { Transition, TransitionChild } from "@headlessui/react";
import { useState, useEffect } from "react";
import { useState, useEffect, useRef } from "react";
import { ArrowRightIcon } from "lucide-react";
import { DiscordIcon } from "@storyteller/icons";
import type { UserInfo } from "@storyteller/api";
import { DesktopLoginBridge } from "./DesktopLoginBridge";
import { LoginSuccess } from "./LoginSuccess";
import { ArtCraftSignUp } from "./artcraft-signup";
import { UsersApi } from "@storyteller/api";
import { getNativeLoginSession, passwordLogin, passwordSignup, isDesktopLoginError } from "./NativeLoginBridge";
import { useLoginModalStore } from "./useLoginModalStore";
const SIGNUP_SOURCE_ARTCRAFT = "artcraft";
// Webapp auth-showcase video (swap by passing `videoUrl`).
const DEFAULT_SHOWCASE_VIDEO =
"https://player.vimeo.com/video/1169289718?background=1&autoplay=1&loop=1&muted=1";
const LOGIN_SUCCESS_DURATION_MS = 3000;
interface LoginModalProps {
onClose?: () => void;
@@ -40,39 +42,56 @@ export function LoginModal({
const [errorMessage, setErrorMessage] = useState("");
const [showDiscord, setShowDiscord] = useState(false);
const [showSuccess, setShowSuccess] = useState(false);
const [isChallengeActive, setIsChallengeActive] = useState(false);
const [loggedInUsername, setLoggedInUsername] = useState<string | null>(null);
const checkArtCraftLogin = async () => {
const usersApi = new UsersApi();
const session = await usersApi.GetSession();
const loggedIn = session.data?.loggedIn;
return loggedIn;
};
const authGeneration = useRef(0);
const authSuccess = useRef(onArtCraftAuthSuccess);
authSuccess.current = onArtCraftAuthSuccess;
const afterClose = useRef(onClose);
afterClose.current = onClose;
// Check session on mount and when recheckTrigger changes.
// A stale startup/recheck response must never reopen the modal after login.
useEffect(() => {
checkArtCraftLogin().then((loggedIn) => {
if (loggedIn) {
const generation = ++authGeneration.current;
let active = true;
getNativeLoginSession().then((user) => {
if (!active || generation !== authGeneration.current) return;
if (user) {
setIsLoggedInArtCraft(true);
authSuccess.current?.(user);
closeModal();
} else {
// Reset modal state to initial values.
setIsLoading(false);
setIsSignUp(initialIsSignUp);
setErrorMessage("");
setShowDiscord(false);
setShowSuccess(false);
setLoggedInUsername(null);
setIsLoggedInArtCraft(false);
const { openModal } = useLoginModalStore.getState();
openModal();
useLoginModalStore.getState().openModal();
}
}).catch((error) => {
if (!active || generation !== authGeneration.current) return;
setErrorMessage(isDesktopLoginError(error) ? error.message : "Unable to check your account. Please sign in again.");
useLoginModalStore.getState().openModal();
});
return () => { active = false; };
}, [recheckTrigger, closeModal, initialIsSignUp]);
useEffect(() => {
if (onOpenChange) onOpenChange(isOpen);
}, [isOpen, onOpenChange]);
useEffect(() => {
if (loggedInUsername === null || !isOpen) return;
const timer = window.setTimeout(() => {
closeModal();
afterClose.current?.();
}, LOGIN_SUCCESS_DURATION_MS);
return () => window.clearTimeout(timer);
}, [loggedInUsername, isOpen, closeModal]);
const handleClose = () => {
closeModal();
onClose?.();
@@ -84,6 +103,15 @@ export function LoginModal({
setShowSuccess(true);
};
const handleLoginSuccess = (user: UserInfo) => {
authGeneration.current += 1;
setIsLoading(false);
setIsLoggedInArtCraft(true);
setIsChallengeActive(false);
setLoggedInUsername(user.username);
authSuccess.current?.(user);
};
const handleAuthSubmit = async (
username: string,
email: string,
@@ -91,56 +119,24 @@ export function LoginModal({
passwordConfirmation: string
) => {
setIsLoading(true);
const usersApi = new UsersApi();
setErrorMessage("");
const generation = ++authGeneration.current;
try {
let signupResponse, loginResponse;
const user = isSignUp
? await passwordSignup(username, email, password, passwordConfirmation)
: await passwordLogin(username || email, password);
if (generation !== authGeneration.current) return;
if (isSignUp) {
signupResponse = await usersApi.Signup({
username,
email,
password,
passwordConfirmation,
signupSource: SIGNUP_SOURCE_ARTCRAFT,
});
if (!signupResponse.success) {
setErrorMessage(
signupResponse.errorMessage || "Signup failed, please try again."
);
setIsLoading(false);
return;
}
loginResponse = await usersApi.Login({
usernameOrEmail: username || email,
password,
});
setIsLoggedInArtCraft(true);
authSuccess.current?.(user);
setShowDiscord(true);
} else {
loginResponse = await usersApi.Login({
usernameOrEmail: username || email,
password,
});
handleLoginSuccess(user);
}
if (!loginResponse.success) {
setErrorMessage(
loginResponse.errorMessage || "Login failed, please try again."
);
setIsLoading(false);
return;
}
setIsLoggedInArtCraft(true);
if (onArtCraftAuthSuccess) {
const session = await usersApi.GetSession();
const userInfo = session.data?.user;
if (userInfo) onArtCraftAuthSuccess(userInfo);
}
setShowDiscord(true); // Onboarding step after successful auth.
} catch (e) {
console.error(e);
setErrorMessage("An unexpected error occurred. Please try again.");
} catch (error) {
if (generation === authGeneration.current) setErrorMessage(isDesktopLoginError(error) ? error.message : "An unexpected error occurred. Please try again.");
} finally {
setIsLoading(false);
if (generation === authGeneration.current) setIsLoading(false);
}
};
@@ -204,7 +200,7 @@ export function LoginModal({
const inOnboarding = showDiscord || showSuccess;
return (
<Transition appear show={isOpen}>
<Transition appear show={isOpen} afterLeave={() => setLoggedInUsername(null)}>
<div className="fixed inset-0 z-[100]">
<TransitionChild
enter="ease-out duration-300"
@@ -226,10 +222,12 @@ export function LoginModal({
leaveTo="opacity-0 scale-95"
>
<div
className="relative flex w-full max-w-5xl overflow-hidden rounded-3xl border border-white/[4%] bg-[#1C1C20] text-white shadow-2xl lg:min-h-[640px]"
className={`relative flex w-full overflow-hidden rounded-3xl border bg-[#1C1C20] text-white shadow-2xl ${loggedInUsername !== null ? "max-w-md border-emerald-200/20" : "max-w-5xl border-white/[4%] lg:min-h-[640px]"}`}
onClick={(e) => e.stopPropagation()}
>
{inOnboarding ? (
{loggedInUsername !== null ? (
<LoginSuccess username={loggedInUsername} />
) : inOnboarding ? (
renderOnboarding()
) : (
<>
@@ -254,13 +252,14 @@ export function LoginModal({
</p>
</div>
<ArtCraftSignUp
{!isSignUp && <DesktopLoginBridge onActiveChange={setIsChallengeActive} onStart={() => { authGeneration.current += 1; }} onSuccess={handleLoginSuccess} />}
{!isChallengeActive && <ArtCraftSignUp
onSubmit={handleAuthSubmit}
isSignUp={isSignUp}
onToggleMode={() => setIsSignUp((prev) => !prev)}
errorMessage={errorMessage}
isLoading={isLoading}
/>
/>}
</div>
</div>
@@ -54,6 +54,9 @@
},
{
"path": "../input/tsconfig.lib.json"
},
{
"path": "../../tauri-api/tsconfig.lib.json"
}
]
}
@@ -3,12 +3,18 @@ import { CommonQuality } from "@storyteller/api-enums";
/**
* Convert a quality value to CommonQuality for the image cost estimate API.
*
* Accepts a CommonQuality string value from @storyteller/model-list ("high", "medium", "low").
* Preserves all API quality tiers, including values added after this build.
*/
export function stringToCommonQuality(
quality: string | undefined,
): string | null {
switch (quality) {
case "auto":
return CommonQuality.Auto;
case "max":
return CommonQuality.Max;
case "xhigh":
return CommonQuality.XHigh;
case "high":
return CommonQuality.High;
case "medium":
@@ -78,7 +78,7 @@ export function useImageCostEstimate(
// Match GenerateImage exactly; omitted values use the API defaults.
aspectRatioStr = imageModel.supportsNewAspectRatio() ? imageAspectRatio : undefined;
resolutionStr = imageModel.supportsNewResolution() ? imageResolution : undefined;
qualityStr = imageModel.supportsQuality() ? imageQuality ?? imageModel.defaultQuality : undefined;
qualityStr = imageModel.resolveQuality(imageQuality);
referenceImageCount = imageModel.canUseImagePrompt
? imageReferenceImages.filter((image) => image.mediaToken.length > 0).length : 0;
generationCount = imageGenerationCount;
@@ -17,6 +17,7 @@ const mocks = vi.hoisted(() => ({
referenceVideos: [{ mediaToken: "mf_video", duration: 7.25 }],
referenceAudios: [{ mediaToken: "mf_audio", duration: 3.5 }],
bitrate: "high",
outputFormat: "mov",
generationCount: 1,
generateWithSound: true,
},
@@ -38,6 +39,7 @@ vi.mock("./cost-breakdown-modal-store", () => ({
}));
beforeEach(() => {
mocks.state.generationCount = 1;
mocks.estimate.mockReset();
mocks.setCredits.mockReset();
mocks.estimate.mockResolvedValue({
@@ -61,6 +63,7 @@ it("quotes a future model with the chosen bitrate and reference durations in mil
model: "future_video",
resolution: "four_k",
bitrate: "high",
output_format: "mov",
duration_seconds: 30,
reference_video_media_tokens: ["mf_video"],
reference_audio_media_tokens: ["mf_audio"],
@@ -72,6 +75,20 @@ it("quotes a future model with the chosen bitrate and reference durations in mil
);
});
it("prices all selected generations for any model with API batch options", async () => {
mocks.state.generationCount = 3;
renderHook(() => useVideoCostEstimate(ModelPage.ImageToVideo, model, "artcraft"));
await waitFor(() => expect(mocks.setCredits).toHaveBeenLastCalledWith(ModelPage.ImageToVideo, 126));
});
it("clears format options and clamps stale batch counts for unsupported models", async () => {
mocks.state.generationCount = 4;
const single = { ...model, generationCountOptions: [1], outputFormatOptions: undefined } as VideoModel;
renderHook(() => useVideoCostEstimate(ModelPage.ImageToVideo, single, "artcraft"));
await waitFor(() => expect(mocks.setCredits).toHaveBeenLastCalledWith(ModelPage.ImageToVideo, 42));
expect(mocks.estimate).toHaveBeenCalledWith(expect.objectContaining({ output_format: undefined }));
});
it("does not overwrite a newer model's quote with a slow earlier response", async () => {
let finishOld: (result: unknown) => void = () => {};
mocks.estimate.mockImplementationOnce(
@@ -111,6 +128,10 @@ const model = {
resolutionOptions: ["4K"],
bitrateOptions: ["normal", "high"],
defaultBitrate: "normal",
outputFormatOptions: ["mp4", "mov"],
defaultOutputFormat: "mp4",
generationCountOptions: [1, 2, 3, 4],
defaultGenerationCount: 1,
generateWithSound: true,
sizeOptions: [{ tauriValue: "wide_sixteen_by_nine", textLabel: "16:9" }],
} as VideoModel;
@@ -1,6 +1,6 @@
import { useEffect, useState } from "react";
import { ModelPage } from "@storyteller/ui-model-selector";
import { Model, VideoModel, resolveVideoDuration, videoResolutionValue } from "@storyteller/model-list";
import { Model, VideoModel, resolveVideoDuration, resolveVideoGenerationCount, resolveVideoOutputFormat, videoResolutionValue } from "@storyteller/model-list";
import { GenerationProvider } from "@storyteller/api-enums";
import { usePromptVideoStore } from "@storyteller/ui-promptbox";
import {
@@ -32,6 +32,7 @@ export function useVideoCostEstimate(
const referenceVideos = usePromptVideoStore((s) => s.referenceVideos);
const referenceAudios = usePromptVideoStore((s) => s.referenceAudios);
const bitrate = usePromptVideoStore((s) => s.bitrate);
const outputFormat = usePromptVideoStore((s) => s.outputFormat);
const generationCount = usePromptVideoStore((s) => s.generationCount);
const generateWithSound = usePromptVideoStore((s) => s.generateWithSound);
@@ -72,6 +73,7 @@ export function useVideoCostEstimate(
duration_seconds: resolveVideoDuration(videoModel, duration, isReferenceMode) ?? undefined,
generate_audio: videoModel.generateWithSound ? generateWithSound : undefined,
bitrate: videoModel.bitrateOptions?.length ? bitrate ?? videoModel.defaultBitrate ?? videoModel.bitrateOptions[0] : undefined,
output_format: resolveVideoOutputFormat(videoModel, outputFormat),
start_frame_image_media_token: !isReferenceMode ? referenceImages[0]?.mediaToken : undefined,
end_frame_image_media_token: !isReferenceMode ? endFrameImage?.mediaToken : undefined,
reference_image_media_tokens: isReferenceMode ? referenceImages.map((image) => image.mediaToken) : undefined,
@@ -88,7 +90,7 @@ export function useVideoCostEstimate(
if (cancelled) return;
if (isEstimateVideoCostSuccess(result)) {
const unitCredits = result.payload.cost_in_credits;
const count = videoModel.id === "seedance_2p0" ? generationCount : 1;
const count = resolveVideoGenerationCount(videoModel, generationCount);
const credits = unitCredits == null ? null : unitCredits * count;
setEstimatedCreditsForPage(ModelPage.ImageToVideo, credits);
} else {
@@ -115,6 +117,7 @@ export function useVideoCostEstimate(
referenceVideos,
referenceAudios,
bitrate,
outputFormat,
generationCount,
endFrameImage,
generateWithSound,
@@ -407,7 +407,7 @@ export const PromptBoxImage = ({
}
if (selectedModel?.supportsQuality()) {
request.quality = commonQuality ?? selectedModel.defaultQuality;
request.quality = selectedModel.resolveQuality(commonQuality);
}
if (
@@ -11,6 +11,9 @@ import { DynamicIcon } from "@storyteller/icons";
import { arrayMove } from "@dnd-kit/sortable";
import {
resolveVideoDuration,
resolveVideoGenerationCount,
resolveVideoOutputFormat,
videoGenerationCounts,
videoDurationRange,
videoResolutionValue,
effectivePromptMaxLength,
@@ -143,6 +146,8 @@ export const PromptBoxVideo = ({
const duration = usePromptVideoStore((s) => s.duration);
const bitrate = usePromptVideoStore((s) => s.bitrate);
const setBitrate = usePromptVideoStore((s) => s.setBitrate);
const outputFormat = usePromptVideoStore((s) => s.outputFormat);
const setOutputFormat = usePromptVideoStore((s) => s.setOutputFormat);
const setDuration = usePromptVideoStore((s) => s.setDuration);
const inputMode = usePromptVideoStore((s) => s.inputMode);
const setInputMode = usePromptVideoStore((s) => s.setInputMode);
@@ -361,6 +366,14 @@ export const PromptBoxVideo = ({
}
}, [selectedModel, setBitrate]);
useEffect(() => {
const current = usePromptVideoStore.getState().outputFormat;
const options = selectedModel?.outputFormatOptions;
if (!current || !options?.includes(current)) {
setOutputFormat(selectedModel?.defaultOutputFormat ?? options?.[0] ?? null);
}
}, [selectedModel, setOutputFormat]);
useEffect(() => {
const current = usePromptVideoStore.getState().aspectRatio;
if (selectedModel?.sizeOptions.some((option) => option.textLabel === current)) return;
@@ -396,15 +409,16 @@ export const PromptBoxVideo = ({
}
}, [selectedModel]);
// Reset generation count when switching away from seedance 2.0.
// Read from store directly to avoid stale closure (same as duration above).
// Keep the selected count within the API's options when switching models.
useEffect(() => {
const currentGenerationCount =
usePromptVideoStore.getState().generationCount;
if (selectedModel?.id !== "seedance_2p0" && currentGenerationCount > 1) {
setGenerationCount(1);
}
}, [selectedModel]);
const current = usePromptVideoStore.getState().generationCount;
const next = selectedModel ? resolveVideoGenerationCount(selectedModel, current) : 1;
if (next !== current) setGenerationCount(next);
}, [selectedModel, setGenerationCount]);
const generationCounts = selectedModel ? videoGenerationCounts(selectedModel) : [1];
const effectiveGenerationCount = selectedModel
? resolveVideoGenerationCount(selectedModel, generationCount) : 1;
const durationRange = selectedModel
? videoDurationRange(selectedModel, inputMode === "reference")
@@ -1049,8 +1063,7 @@ export const PromptBoxVideo = ({
gtagEvent("enqueue_video");
const isSeedance2 = selectedModel.id === "seedance_2p0";
const count = isSeedance2 ? generationCount : 1;
const count = effectiveGenerationCount;
const isRefMode =
inputMode === "reference" && !!selectedModel.supportsReferenceMode;
@@ -1145,6 +1158,9 @@ export const PromptBoxVideo = ({
if (selectedModel.bitrateOptions?.length) {
request.bitrate = bitrate ?? selectedModel.defaultBitrate ?? selectedModel.bitrateOptions[0];
}
if (selectedModel.outputFormatOptions?.length) {
request.output_format = resolveVideoOutputFormat(selectedModel, outputFormat);
}
// Pass the chosen resolution when the model exposes a resolution picker.
// Guarded on `resolutionOptions` so a stale store value (left over from a
@@ -1454,6 +1470,21 @@ export const PromptBoxVideo = ({
</Tooltip>
)}
{!!selectedModel?.outputFormatOptions?.length && (
<Tooltip content="Output format" position="top" className="z-50">
<PopoverMenu
panelTitle="Output format"
mode="toggle"
items={selectedModel.outputFormatOptions.map((value) => ({
label: value.toUpperCase(),
action: value,
selected: value === outputFormat,
}))}
onSelect={(item) => setOutputFormat(item.action ?? item.label)}
/>
</Tooltip>
)}
{durationRange && durationRange.max > durationRange.min && (
<Tooltip content="Duration" position="top" className="z-50">
<PopoverMenu
@@ -1522,10 +1553,10 @@ export const PromptBoxVideo = ({
disabled={!hasClearableContent}
confirmClear={hasAttachedRefs}
/>
{selectedModel?.id === "seedance_2p0" && (
{generationCounts.length > 1 && (
<VideoGenerationCountPicker
maxCount={4}
currentCount={generationCount}
counts={generationCounts}
currentCount={effectiveGenerationCount}
handleCountChange={setGenerationCount}
/>
)}
@@ -1541,9 +1572,7 @@ export const PromptBoxVideo = ({
onClick={handleEnqueue}
disabled={!prompt.trim()}
loading={isEnqueueing}
credits={
credits != null ? credits * generationCount : credits
}
credits={credits}
/>
</div>
</Tooltip>
@@ -10,6 +10,9 @@ interface QualityPickerProps {
}
const QUALITY_LABELS: Record<CommonQuality, string> = {
[CommonQuality.Auto]: "Auto",
[CommonQuality.Max]: "Max",
[CommonQuality.XHigh]: "Extra high",
[CommonQuality.High]: "High",
[CommonQuality.Medium]: "Medium",
[CommonQuality.Low]: "Low",
@@ -17,7 +20,7 @@ const QUALITY_LABELS: Record<CommonQuality, string> = {
/**
* Stateless picker for image generation "quality" (used by OpenAI image
* models — gpt_image_1, gpt_image_1p5, gpt_image_2). Models that don't
* models, including GPT Image 2.5). Models that don't
* declare `qualities` should not render this picker.
*/
export const QualityPicker = ({
@@ -25,7 +28,7 @@ export const QualityPicker = ({
currentQuality,
handleCommonQualitySelect,
}: QualityPickerProps) => {
const useQuality = currentQuality ?? model.defaultQuality ?? undefined;
const useQuality = model.resolveQuality(currentQuality);
const handleSelectAdapter = (item: PopoverItem) => {
const quality = (item.action ?? item.label) as CommonQuality;
@@ -4,27 +4,24 @@ import { Tooltip } from "@storyteller/ui-tooltip";
import { PROMPT_TOOLBAR_ICON_BUTTON_CLASSES } from "../PromptClearAllButton";
interface VideoGenerationCountPickerProps {
maxCount: number;
counts: number[];
currentCount: number;
handleCountChange: (count: number) => void;
}
export const VideoGenerationCountPicker = ({
maxCount,
counts,
currentCount,
handleCountChange,
}: VideoGenerationCountPickerProps) => {
const options: PopoverItem[] = [];
for (let i = 1; i <= maxCount; i++) {
options.push({
label: String(i),
selected: i === currentCount,
});
}
const options: PopoverItem[] = counts.map((count) => ({
label: String(count),
selected: count === currentCount,
}));
const onSelect = (item: PopoverItem) => {
const count = parseInt(item.label, 10);
if (!isNaN(count) && count >= 1 && count <= maxCount) {
if (counts.includes(count)) {
handleCountChange(count);
}
};
@@ -165,6 +165,7 @@ interface PromptVideoStore {
generateWithSound: boolean;
duration: number | null;
bitrate: string | null;
outputFormat: string | null;
inputMode: VideoInputMode;
generationCount: number;
setPrompt: (prompt: string) => void;
@@ -178,6 +179,7 @@ interface PromptVideoStore {
setGenerateWithSound: (value: boolean) => void;
setDuration: (duration: number | null) => void;
setBitrate: (bitrate: string | null) => void;
setOutputFormat: (outputFormat: string | null) => void;
setInputMode: (mode: VideoInputMode) => void;
setGenerationCount: (count: number) => void;
}
@@ -194,6 +196,7 @@ export const usePromptVideoStore = create<PromptVideoStore>()((set) => ({
generateWithSound: true,
duration: null,
bitrate: null,
outputFormat: null,
inputMode: "reference",
generationCount: 1,
setPrompt: (prompt) => set({ prompt }),
@@ -207,6 +210,7 @@ export const usePromptVideoStore = create<PromptVideoStore>()((set) => ({
setGenerateWithSound: (generateWithSound) => set({ generateWithSound }),
setDuration: (duration) => set({ duration }),
setBitrate: (bitrate) => set({ bitrate }),
setOutputFormat: (outputFormat) => set({ outputFormat }),
setInputMode: (inputMode) => set({ inputMode }),
setGenerationCount: (generationCount) => set({ generationCount }),
}));
@@ -189,6 +189,13 @@ export class ImageModel extends Model {
return this.qualityOptions && this.qualityOptions.length > 0;
}
// A saved tier from another model may not be supported by this model.
resolveQuality(current?: CommonQuality): CommonQuality | undefined {
if (!this.supportsQuality()) return undefined;
return current && this.qualityOptions.includes(current)
? current : this.defaultQuality ?? this.qualityOptions[0];
}
// Return whether the count of generations is valid for this model
isValidGenerationCount(count: number): boolean {
if (this.predefinedGenerationCounts) {
@@ -41,6 +41,10 @@ export class VideoModel extends Model {
readonly maxDurationWithImageReferences?: number;
readonly bitrateOptions?: string[];
readonly defaultBitrate?: string;
readonly outputFormatOptions?: string[];
readonly defaultOutputFormat?: string;
readonly generationCountOptions?: number[];
readonly defaultGenerationCount?: number;
readonly defaultAspectRatio?: string;
@@ -102,6 +106,10 @@ export class VideoModel extends Model {
maxDurationWithImageReferences?: number;
bitrateOptions?: string[];
defaultBitrate?: string;
outputFormatOptions?: string[];
defaultOutputFormat?: string;
generationCountOptions?: number[];
defaultGenerationCount?: number;
defaultAspectRatio?: string;
supportsReferenceMode?: boolean;
@@ -130,6 +138,10 @@ export class VideoModel extends Model {
this.maxDurationWithImageReferences = args.maxDurationWithImageReferences;
this.bitrateOptions = args.bitrateOptions;
this.defaultBitrate = args.defaultBitrate;
this.outputFormatOptions = args.outputFormatOptions;
this.defaultOutputFormat = args.defaultOutputFormat;
this.generationCountOptions = args.generationCountOptions;
this.defaultGenerationCount = args.defaultGenerationCount;
this.defaultAspectRatio = args.defaultAspectRatio;
this.supportsReferenceMode = args.supportsReferenceMode;
@@ -24,6 +24,7 @@ export const MODEL_ID_PREFIX_CREATORS: Array<[string, ModelCreator]> = [
["vidu", ModelCreator.Vidu],
["recraft", ModelCreator.Recraft],
["happy_horse", ModelCreator.Alibaba],
["wan", ModelCreator.Alibaba],
["minimax", ModelCreator.Hailuo],
["qwen", ModelCreator.Alibaba],
["suno", ModelCreator.Suno],
@@ -13,6 +13,7 @@ const MODEL_ID_PREFIX_FAMILIES: Array<[string, string]> = [
["minimax", "MiniMax"],
["hailuo", "MiniMax"],
["happy_horse", "Happy Horse"],
["wan", "Wan"],
["vidu", "Vidu"],
// ── Image ── (flux also covers the Flux 3 video model)
["flux", "Flux"],
@@ -50,6 +51,7 @@ export const FAMILY_ORDER: string[] = [
"Grok",
"Vidu",
"Happy Horse",
"Wan",
// Image families.
"Nano Banana",
"Seedream",
@@ -96,7 +96,10 @@ export const getModelDisplayName = (
seedance_2p0_bpu_fast: "Seedance 2.0 Plus Ultra Fast",
seedance_2p0_bpu_mini: "Seedance 2.0 Plus Ultra Mini",
seedance_2p5: "Seedance 2.5",
seedance_2p5_u: "Seedance 2.5 Ultra",
seedance_2p5_preview: "Seedance 2.5 Preview",
wan_3p0: "Wan 3.0",
wan_3p0_prime: "Wan 3.0 Prime",
// Seedance — dot-normalized aliases
seedance_1_0_lite: "Seedance 1.0 Lite",
// Anonymous preview aliases the backend used pre-announce
@@ -2,6 +2,9 @@
/// Not all models have each of these qualities,
/// but Tauri will interpolate if a mistake is sent.
export enum CommonQuality {
Auto = "auto",
Max = "max",
XHigh = "xhigh",
High = "high",
Medium = "medium",
Low = "low",
@@ -1,5 +1,23 @@
import type { VideoModel } from "./VideoModel.js";
export function resolveVideoOutputFormat(model: VideoModel, current?: string | null): string | undefined {
const options = model.outputFormatOptions;
if (!options?.length) return undefined;
if (current && options.includes(current)) return current;
return model.defaultOutputFormat ?? options[0];
}
export function videoGenerationCounts(model: VideoModel): number[] {
return model.generationCountOptions?.length ? model.generationCountOptions : [1];
}
export function resolveVideoGenerationCount(model: VideoModel, current: number): number {
const options = videoGenerationCounts(model);
if (options.includes(current)) return current;
return model.defaultGenerationCount != null && options.includes(model.defaultGenerationCount)
? model.defaultGenerationCount : options[0];
}
/** Normalize old display values while preserving future API values. */
export function videoResolutionValue(value: string): string {
const legacy: Record<string, string> = {
@@ -403,7 +403,7 @@ export const IMAGE_MODELS: ImageModel[] = [
progressBarTime: 60000,
maxPromptLength: Infinity,
canChangeAspectRatio: true,
defaultAspectRatio: CommonAspectRatio.WideSixteenByNine,
defaultAspectRatio: CommonAspectRatio.Square,
aspectRatios: [
CommonAspectRatio.Auto,
CommonAspectRatio.Square,
@@ -413,8 +413,19 @@ export const IMAGE_MODELS: ImageModel[] = [
CommonAspectRatio.WideFourByThree,
CommonAspectRatio.WideSixteenByNine,
],
canChangeResolution: true,
resolutions: [
CommonResolution.OneK,
CommonResolution.TwoK,
CommonResolution.ThreeK,
CommonResolution.FourK,
],
defaultResolution: CommonResolution.OneK,
defaultQuality: CommonQuality.High,
qualityOptions: [
CommonQuality.Auto,
CommonQuality.Max,
CommonQuality.XHigh,
CommonQuality.High,
CommonQuality.Medium,
CommonQuality.Low,
@@ -438,7 +449,7 @@ export const IMAGE_MODELS: ImageModel[] = [
progressBarTime: 120000,
maxPromptLength: Infinity,
canChangeAspectRatio: true,
defaultAspectRatio: CommonAspectRatio.WideSixteenByNine,
defaultAspectRatio: CommonAspectRatio.Square,
aspectRatios: [
CommonAspectRatio.Auto,
CommonAspectRatio.Square,
@@ -448,8 +459,19 @@ export const IMAGE_MODELS: ImageModel[] = [
CommonAspectRatio.WideFourByThree,
CommonAspectRatio.WideSixteenByNine,
],
canChangeResolution: true,
resolutions: [
CommonResolution.OneK,
CommonResolution.TwoK,
CommonResolution.ThreeK,
CommonResolution.FourK,
],
defaultResolution: CommonResolution.OneK,
defaultQuality: CommonQuality.High,
qualityOptions: [
CommonQuality.Auto,
CommonQuality.Max,
CommonQuality.XHigh,
CommonQuality.High,
CommonQuality.Medium,
CommonQuality.Low,
@@ -345,6 +345,8 @@ export const VIDEO_MODELS: VideoModel[] = [
new VideoModel({
id: "seedance_2p0",
tauriId: "seedance_2p0",
generationCountOptions: [1, 2, 3, 4],
defaultGenerationCount: 1,
fullName: "Seedance 2.0",
category: "video",
creator: ModelCreator.Bytedance,
@@ -7,10 +7,14 @@ import {
} from "./buildModelsFromListing.js";
import {
resolveVideoDuration,
resolveVideoGenerationCount,
resolveVideoOutputFormat,
videoGenerationCounts,
videoDurationRange,
videoResolutionValue,
} from "../classes/videoOptions.js";
import { IMAGE_MODELS } from "../lists/ImageModels.js";
import { CommonQuality } from "../classes/properties/CommonQuality.js";
import { VIDEO_MODELS } from "../lists/VideoModels.js";
import { SPLAT_MODELS } from "../lists/SplatModels.js";
@@ -24,6 +28,8 @@ describe("desktop catalog", () => {
"flux_3",
"minimax_h3",
"vidu_q3",
"wan_3p0",
"wan_3p0_prime",
"future_video_v99",
];
const models = buildVideoModelsFromListing(
@@ -97,6 +103,61 @@ describe("desktop catalog", () => {
});
describe("API video options", () => {
it.each(["wan_3p0", "wan_3p0_prime"])("hydrates %s with Wan's reference and duration capabilities", (id) => {
const [model] = buildVideoModelsFromListing([], [{
model: id,
model_creator: "alibaba",
text_to_video_supported: true,
text_prompt_max_length: 20000,
starting_keyframe_supported: true,
ending_keyframe_supported: true,
image_references_supported: true,
image_references_max: 10,
video_references_max: 5,
video_references_max_total_duration_seconds: 15,
audio_references_max: 5,
audio_references_max_total_duration_seconds: 15,
show_generate_with_sound_toggle: true,
resolution_options: ["four_eighty_p", "seven_twenty_p", "ten_eighty_p"],
resolution_default: "seven_twenty_p",
duration_seconds_min: 2,
duration_seconds_max: 30,
duration_seconds_default: 5,
batch_size_options: [1],
batch_size_default: 1,
}]);
expect(model.getProviders()).toEqual([GenerationProvider.Artcraft]);
expect(model).toMatchObject({
startFrame: true, endFrame: true, textToVideoSupported: true,
supportsReferenceMode: true, maxReferenceImages: 10,
maxReferenceVideos: 5, maxVideoRefDuration: 15,
maxReferenceAudios: 5, maxAudioRefDuration: 15,
generateWithSound: true, maxPromptLength: 20000,
resolutionOptions: ["480p", "720p", "1080p"], defaultResolution: "720p",
});
expect(videoDurationRange(model, true)).toEqual({ min: 2, max: 30 });
expect(resolveVideoDuration(model, null, false)).toBe(5);
expect(videoGenerationCounts(model)).toEqual([1]);
expect(resolveVideoGenerationCount(model, 4)).toBe(1);
});
it.each(["seedance_2p5", "seedance_2p5_u"])("preserves %s output formats and batch choices", (id) => {
const [model] = buildVideoModelsFromListing([], [{
model: id,
output_format_options: ["mp4", "mov", "future_format"],
output_format_default: "mp4",
batch_size_options: [1, 2, 3, 4],
batch_size_default: 1,
}]);
expect(model.outputFormatOptions).toEqual(["mp4", "mov", "future_format"]);
expect(model.defaultOutputFormat).toBe("mp4");
expect(resolveVideoOutputFormat(model, "mov")).toBe("mov");
expect(resolveVideoOutputFormat(model, "unsupported")).toBe("mp4");
expect(videoGenerationCounts(model)).toEqual([1, 2, 3, 4]);
expect(resolveVideoGenerationCount(model, 3)).toBe(3);
expect(resolveVideoGenerationCount(model, 5)).toBe(1);
});
it("uses range durations, reference-mode caps, bitrate, and future resolutions", () => {
const [model] = buildVideoModelsFromListing(
[],
@@ -134,6 +195,37 @@ describe("API video options", () => {
});
});
it.each(["gpt_image_2p5_flare", "gpt_image_2p5_sunburst"])("preserves every %s quality and resolution option", (id) => {
const qualities = ["auto", "max", "xhigh", "high", "medium", "low"];
const resolutions = ["one_k", "two_k", "three_k", "four_k"];
const model = buildImageModelsFromListing(IMAGE_MODELS, [{
model: id,
quality_options: qualities,
default_quality: "high",
resolution_options: resolutions,
resolution_default: "one_k",
image_refs_supported: true,
}]).find((m) => m.tauriId === id)!;
expect(model.qualityOptions).toEqual(qualities);
expect(model.defaultQuality).toBe("high");
expect(model.resolutions).toEqual(resolutions);
expect(model.defaultResolution).toBe("one_k");
expect(model.canEditImages).toBe(true);
expect(model.resolveQuality(CommonQuality.Max)).toBe("max");
expect(model.resolveQuality(CommonQuality.Auto)).toBe("auto");
});
it("uses the new model's default when a saved quality tier is unsupported", () => {
const [model] = buildImageModelsFromListing([], [{
model: "gpt_image_2",
quality_options: ["high", "medium", "low"],
default_quality: "high",
}]);
expect(model.resolveQuality(CommonQuality.Max)).toBe("high");
expect(model.resolveQuality(CommonQuality.XHigh)).toBe("high");
expect(model.resolveQuality(CommonQuality.Low)).toBe("low");
});
it("offers ArtCraft and direct Midjourney only for supported Midjourney models", () => {
const models = buildImageModelsFromListing([], [
{ model: "midjourney_7" }, { model: "midjourney_7_niji" },
@@ -76,6 +76,8 @@ export interface ListingVideoModel extends ListingModelBase {
duration_seconds_max_with_image_references?: number | null;
bitrate_options?: string[] | null;
bitrate_default?: string | null;
output_format_options?: string[] | null;
output_format_default?: string | null;
duration_seconds_default?: number | null;
}
@@ -269,6 +271,10 @@ const mergedVideoModel = (
maxDurationWithImageReferences: m.duration_seconds_max_with_image_references ?? o?.maxDurationWithImageReferences,
bitrateOptions: m.bitrate_options ?? o?.bitrateOptions,
defaultBitrate: m.bitrate_default ?? o?.defaultBitrate,
outputFormatOptions: m.output_format_options ?? o?.outputFormatOptions,
defaultOutputFormat: m.output_format_default ?? o?.defaultOutputFormat,
generationCountOptions: m.batch_size_options ?? o?.generationCountOptions,
defaultGenerationCount: m.batch_size_default ?? o?.defaultGenerationCount,
defaultAspectRatio: m.aspect_ratio_default ?? o?.defaultAspectRatio,
supportsReferenceMode: m.image_references_supported ?? o?.supportsReferenceMode,
maxReferenceImages: m.image_references_max ?? o?.maxReferenceImages,

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