feat: unify product name and build flavor across builds

Signed-off-by: hazre <[email protected]>
This commit is contained in:
hazre authored and 7w1 committed 2026-07-26 13:32:41 -05:00
1 parent 4815ba65e2
commit 0e72405875
46 files changed
+417 -276

No files matched your search

@@ -0,0 +1,5 @@
---
default: patch
---
Settings device name now clearly shows your device type — e.g. "Sable Desktop on Windows", "Sable Mobile on Android", or "Sable Web on Firefox for macOS"
+2 -2
View File
@@ -3,7 +3,7 @@ description: Prepares OpenTofu in infra/web.
inputs:
is_release_tag:
description: Whether the build is for a release tag. Passed through to VITE_IS_RELEASE_TAG.
description: Whether the build is for a release tag. Passed through to SABLE_BUILD_FLAVOR.
required: false
default: 'false'
@@ -15,7 +15,7 @@ runs:
with:
build: 'true'
env:
VITE_IS_RELEASE_TAG: ${{ inputs.is_release_tag }}
SABLE_BUILD_FLAVOR: ${{ inputs.is_release_tag == 'true' && 'stable' || '' }}
VITE_SENTRY_DSN: ${{ env.VITE_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ env.VITE_SENTRY_ENVIRONMENT }}
VITE_APP_VERSION: ${{ env.VITE_APP_VERSION }}
@@ -0,0 +1,41 @@
name: Resolve release meta
description: Detect whether the current build is a nightly/dev or stable release and output tag, version, ref, and build flavor.
inputs:
input-tag:
description: Explicit tag for workflow_dispatch triggers
required: false
default: ''
outputs:
tag:
description: Release tag name (e.g. "nightly" or "v1.2.3")
value: ${{ steps.meta.outputs.tag }}
version:
description: SemVer version string
value: ${{ steps.meta.outputs.version }}
ref:
description: Git ref (sha for nightly, tag ref for stable)
value: ${{ steps.meta.outputs.ref }}
nightly:
description: '"true" if this is a nightly/dev build'
value: ${{ steps.meta.outputs.nightly }}
started_at:
description: ISO 8601 timestamp of when the build started
value: ${{ steps.meta.outputs.started_at }}
build_flavor:
description: '"dev" or "stable"'
value: ${{ steps.meta.outputs.build_flavor }}
runs:
using: composite
steps:
- shell: bash
id: meta
env:
EVENT_NAME: ${{ github.event_name }}
INPUT_TAG: ${{ inputs.input-tag }}
GIT_REF: ${{ github.ref }}
GIT_REF_NAME: ${{ github.ref_name }}
GIT_SHA: ${{ github.sha }}
run: node ${{ github.action_path }}/../../scripts/release-meta.mjs "$GITHUB_OUTPUT"
+10 -1
View File
@@ -6,6 +6,7 @@ import { execSync } from 'node:child_process';
import { readFileSync, readdirSync, writeFileSync, mkdtempSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { resolveReleaseMeta } from './release-meta.mjs';
const TAG = process.env.TAG;
const VERSION = process.env.VERSION;
@@ -20,6 +21,14 @@ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/.test(VERSION)) {
}
const version = VERSION;
const { isNightly } = resolveReleaseMeta({
eventName: process.env.EVENT_NAME,
inputTag: process.env.INPUT_TAG,
gitRef: process.env.GIT_REF,
gitRefName: process.env.GIT_REF_NAME,
gitSha: process.env.GIT_SHA,
});
const dir = mkdtempSync(join(tmpdir(), 'sable-sigs-'));
execSync(`gh release download "${TAG}" --repo "${REPO}" --pattern '*.sig' --dir "${dir}"`, {
stdio: 'inherit',
@@ -55,7 +64,7 @@ if (Object.keys(platforms).length === 0) {
}
let notes = `Sable ${version}`;
if (TAG !== 'nightly') {
if (!isNightly) {
try {
notes =
execSync(`gh release view "${TAG}" --repo "${REPO}" --json body -q .body`, {
-40
View File
@@ -1,40 +0,0 @@
#!/usr/bin/env node
/* oxlint-disable no-console */
import { execSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
const packageJson = JSON.parse(readFileSync('package.json', 'utf8'));
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(packageJson.version);
if (!match) {
console.error(`package.json version must be stable SemVer (got: ${packageJson.version})`);
process.exit(1);
}
let timestamp;
try {
// Read the HEAD commit's committer timestamp in UTC epoch seconds
const commitTimestamp = execSync('git log -1 --format=%ct', {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
if (/^\d+$/.test(commitTimestamp)) {
timestamp = new Date(Number(commitTimestamp) * 1000);
}
} catch {
// Fallback to current system time if git is unavailable
}
timestamp ||= new Date();
const year = String(timestamp.getUTCFullYear()).slice(-2);
const month = String(timestamp.getUTCMonth() + 1).padStart(2, '0');
const day = String(timestamp.getUTCDate()).padStart(2, '0');
const hours = String(timestamp.getUTCHours()).padStart(2, '0');
const minutes = String(timestamp.getUTCMinutes()).padStart(2, '0');
const timeIdentifier = `${year}${month}${day}${hours}${minutes}`;
const [, major, minor, patch] = match;
console.log(`${major}.${minor}.${Number(patch) + 1}-nightly.${timeIdentifier}`);
+118
View File
@@ -0,0 +1,118 @@
#!/usr/bin/env node
/* oxlint-disable no-console */
import { execSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
export function computeNightlyVersion(baseVersion, timestamp = new Date()) {
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(baseVersion);
if (!match) {
throw new Error(`Version must be stable SemVer (got: ${baseVersion})`);
}
const y = String(timestamp.getUTCFullYear()).slice(-2);
const m = String(timestamp.getUTCMonth() + 1).padStart(2, '0');
const d = String(timestamp.getUTCDate()).padStart(2, '0');
const h = String(timestamp.getUTCHours()).padStart(2, '0');
const min = String(timestamp.getUTCMinutes()).padStart(2, '0');
const [, major, minor, patch] = match;
return `${major}.${minor}.${Number(patch) + 1}-nightly.${y}${m}${d}${h}${min}`;
}
export function nightlyVersion() {
const { version } = JSON.parse(readFileSync('package.json', 'utf8'));
let timestamp;
try {
const commitTimestamp = execSync('git log -1 --format=%ct', {
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
if (/^\d+$/.test(commitTimestamp)) {
timestamp = new Date(Number(commitTimestamp) * 1000);
}
} catch {}
return computeNightlyVersion(version, timestamp);
}
export async function writeOutputs(outputPath, entries) {
const { appendFileSync } = await import('node:fs');
appendFileSync(outputPath, entries.map((e) => `${e.key}=${e.value}`).join('\n') + '\n');
}
export function resolveReleaseMeta({
eventName = '',
inputTag = '',
gitRef = '',
gitRefName = '',
gitSha = '',
} = {}) {
const startedAt = new Date().toISOString();
let tag, ref, isNightly, version;
if (eventName === 'workflow_dispatch' && inputTag) {
tag = inputTag;
ref = inputTag;
isNightly = false;
version = tag.replace(/^v/, '');
} else if (gitRef === 'refs/heads/dev') {
tag = 'nightly';
ref = gitSha;
isNightly = true;
version = nightlyVersion();
} else if (/^v\d+\./.test(gitRefName)) {
tag = gitRefName;
ref = gitRef;
isNightly = false;
version = gitRefName.replace(/^v/, '');
} else {
tag = '';
ref = gitRef;
isNightly = false;
version = '';
}
return {
tag,
version,
ref,
isNightly,
startedAt,
buildFlavor: isNightly ? 'dev' : 'stable',
};
}
const isMain =
process.argv[1] && import.meta.url === `file:///${process.argv[1].replace(/\\/g, '/')}`;
if (isMain) {
try {
const meta = resolveReleaseMeta({
eventName: process.env.EVENT_NAME ?? '',
inputTag: process.env.INPUT_TAG ?? '',
gitRef: process.env.GIT_REF ?? '',
gitRefName: process.env.GIT_REF_NAME ?? '',
gitSha: process.env.GIT_SHA ?? '',
});
const outputPath = process.argv[2];
const entries = [
{ key: 'tag', value: meta.tag },
{ key: 'version', value: meta.version },
{ key: 'ref', value: meta.ref },
{ key: 'nightly', value: String(meta.isNightly) },
{ key: 'started_at', value: meta.startedAt },
{ key: 'build_flavor', value: meta.buildFlavor },
];
if (outputPath) {
await writeOutputs(outputPath, entries);
} else {
entries.forEach(({ key, value }) => console.log(`${key}=${value}`));
}
} catch (err) {
console.error(err.message);
process.exit(1);
}
}
+1 -6
View File
@@ -41,13 +41,8 @@ jobs:
with:
persist-credentials: false
- name: Compute nightly version
- uses: ./.github/actions/resolve-release-meta
id: version
shell: bash
working-directory: ${{ github.workspace }}
run: |
VERSION="$(node .github/scripts/nightly-version.mjs)"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Prepare OpenTofu deployment
uses: ./.github/actions/prepare-tofu
+12 -30
View File
@@ -45,28 +45,10 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Resolve release tag value
id: release_tag
shell: bash
run: |
if [[ "${{ github.event_name }}" == "workflow_dispatch" && -n "${INPUTS_GIT_TAG}" ]]; then
TAG="${INPUTS_GIT_TAG}"
else
TAG="${GITHUB_REF#refs/tags/}"
fi
if [[ "${TAG}" == v* ]]; then
echo "value=${TAG#v}" >> "$GITHUB_OUTPUT"
echo "is_release=true" >> "$GITHUB_OUTPUT"
elif [[ "${GITHUB_REF}" == "refs/heads/dev" ]]; then
NIGHTLY_VERSION="$(node .github/scripts/nightly-version.mjs)"
echo "value=${NIGHTLY_VERSION}" >> "$GITHUB_OUTPUT"
echo "is_release=true" >> "$GITHUB_OUTPUT"
else
echo "value=" >> "$GITHUB_OUTPUT"
echo "is_release=false" >> "$GITHUB_OUTPUT"
fi
env:
INPUTS_GIT_TAG: ${{ inputs.git_tag }}
- uses: ./.github/actions/resolve-release-meta
id: release_meta
with:
input-tag: ${{ inputs.git_tag }}
- name: Extract metadata
id: meta
@@ -77,14 +59,14 @@ jobs:
latest=false
tags: |
# dev branch or manual dispatch without a tag: short commit SHA + dev
type=sha,prefix=,format=short,enable=${{ github.ref == 'refs/heads/dev' || (github.event_name == 'workflow_dispatch' && inputs.git_tag == '') }}
type=raw,value=dev,enable=${{ github.ref == 'refs/heads/dev' || (github.event_name == 'workflow_dispatch' && inputs.git_tag == '') }}
type=sha,prefix=,format=short,enable=${{ steps.release_meta.outputs.version != '' && steps.release_meta.outputs.nightly == 'true' }}
type=raw,value=dev,enable=${{ steps.release_meta.outputs.version != '' && steps.release_meta.outputs.nightly == 'true' }}
# git tags (push or manual dispatch with a tag): semver breakdown + latest
type=raw,value=latest,enable=${{ steps.release_tag.outputs.is_release == 'true' }}
type=semver,pattern={{version}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }}
type=semver,pattern={{major}}.{{minor}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' }}
type=semver,pattern={{major}},value=${{ steps.release_tag.outputs.value }},enable=${{ steps.release_tag.outputs.is_release == 'true' && !startsWith(steps.release_tag.outputs.value, 'v0.') }}
type=raw,value=latest,enable=${{ steps.release_meta.outputs.version != '' }}
type=semver,pattern={{version}},value=${{ steps.release_meta.outputs.version }},enable=${{ steps.release_meta.outputs.version != '' }}
type=semver,pattern={{major}}.{{minor}},value=${{ steps.release_meta.outputs.version }},enable=${{ steps.release_meta.outputs.version != '' }}
type=semver,pattern={{major}},value=${{ steps.release_meta.outputs.version }},enable=${{ steps.release_meta.outputs.version != '' && !startsWith(steps.release_meta.outputs.version, 'v0.') }}
- name: Compute short SHA
id: vars
@@ -96,8 +78,8 @@ jobs:
- name: Build site
env:
VITE_BUILD_HASH: ${{ steps.vars.outputs.short_sha }}
VITE_APP_VERSION: ${{ steps.release_tag.outputs.value }}
VITE_IS_RELEASE_TAG: ${{ steps.release_tag.outputs.is_release }}
VITE_APP_VERSION: ${{ steps.release_meta.outputs.version }}
SABLE_BUILD_FLAVOR: ${{ steps.release_meta.outputs.build_flavor }}
run: |
NODE_OPTIONS=--max_old_space_size=4096 pnpm run build
+13 -40
View File
@@ -39,36 +39,10 @@ jobs:
with:
persist-credentials: false
- name: Resolve target
- uses: ./.github/actions/resolve-release-meta
id: meta
shell: bash
env:
EVENT_NAME: ${{ github.event_name }}
INPUT_TAG: ${{ inputs.tag }}
GIT_REF: ${{ github.ref }}
GIT_REF_NAME: ${{ github.ref_name }}
GIT_SHA: ${{ github.sha }}
RUN_NUMBER: ${{ github.run_number }}
RUN_ATTEMPT: ${{ github.run_attempt }}
run: |
STARTED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
if [ "$EVENT_NAME" = "workflow_dispatch" ]; then
TAG="$INPUT_TAG"; REF="$INPUT_TAG"; NIGHTLY=false
VERSION="${TAG#v}"
elif [ "$GIT_REF" = "refs/heads/dev" ]; then
TAG="nightly"; REF="$GIT_SHA"; NIGHTLY=true
VERSION="$(node .github/scripts/nightly-version.mjs)"
else
TAG="$GIT_REF_NAME"; REF="$GIT_REF"; NIGHTLY=false
VERSION="${TAG#v}"
fi
{
echo "tag=$TAG"
echo "version=$VERSION"
echo "ref=$REF"
echo "nightly=$NIGHTLY"
echo "started_at=$STARTED_AT"
} >> "$GITHUB_OUTPUT"
with:
input-tag: ${{ inputs.tag }}
- name: Wait for release to exist
if: ${{ steps.meta.outputs.nightly != 'true' }}
@@ -139,7 +113,7 @@ jobs:
TAG: ${{ needs.setup-release.outputs.tag }}
VERSION: ${{ needs.setup-release.outputs.version }}
VITE_APP_VERSION: ${{ needs.setup-release.outputs.version }}
VITE_IS_RELEASE_TAG: ${{ needs.setup-release.outputs.nightly == 'true' && 'true' || '' }}
SABLE_BUILD_FLAVOR: ${{ needs.setup-release.outputs.nightly == 'true' && 'dev' || 'stable' }}
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ needs.setup-release.outputs.nightly == 'true' && 'preview' || 'production' }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
@@ -192,7 +166,7 @@ jobs:
ARGS="$ARGS --bundles nsis"
fi
if [ "$IS_NIGHTLY" = "true" ]; then
ARGS="$ARGS --config src-tauri/tauri.nightly.conf.json"
echo "SABLE_BUILD_FLAVOR=dev" >> "$GITHUB_ENV"
fi
echo "TAURI_BUILD_ARGS=${ARGS# }" >> "$GITHUB_ENV"
@@ -326,7 +300,7 @@ jobs:
TAG: ${{ needs.setup-release.outputs.tag }}
VERSION: ${{ needs.setup-release.outputs.version }}
VITE_APP_VERSION: ${{ needs.setup-release.outputs.version }}
VITE_IS_RELEASE_TAG: ${{ needs.setup-release.outputs.nightly == 'true' && 'true' || '' }}
SABLE_BUILD_FLAVOR: ${{ needs.setup-release.outputs.nightly == 'true' && 'dev' || 'stable' }}
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ needs.setup-release.outputs.nightly == 'true' && 'preview' || 'production' }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
@@ -393,11 +367,10 @@ jobs:
env:
IS_NIGHTLY: ${{ needs.setup-release.outputs.nightly }}
run: |
ARGS=()
if [ "$IS_NIGHTLY" = "true" ]; then
ARGS+=(--config src-tauri/tauri.nightly.conf.json)
export SABLE_BUILD_FLAVOR=dev
fi
pnpm tauri android build --apk --aab --target aarch64 armv7 "${ARGS[@]}"
pnpm tauri android build --apk --aab --target aarch64 armv7
OUT='src-tauri/gen/android/app/build/outputs'
APK=$(find "$OUT/apk/universal/release" -name '*.apk' -type f | head -1)
AAB=$(find "$OUT/bundle/universalRelease" -name '*.aab' -type f | head -1)
@@ -440,7 +413,7 @@ jobs:
TAG: ${{ needs.setup-release.outputs.tag }}
VERSION: ${{ needs.setup-release.outputs.version }}
VITE_APP_VERSION: ${{ needs.setup-release.outputs.version }}
VITE_IS_RELEASE_TAG: ${{ needs.setup-release.outputs.nightly == 'true' && 'true' || '' }}
SABLE_BUILD_FLAVOR: ${{ needs.setup-release.outputs.nightly == 'true' && 'dev' || 'stable' }}
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
VITE_SENTRY_ENVIRONMENT: ${{ needs.setup-release.outputs.nightly == 'true' && 'preview' || 'production' }}
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
@@ -489,11 +462,10 @@ jobs:
env:
IS_NIGHTLY: ${{ needs.setup-release.outputs.nightly }}
run: |
ARGS=()
if [ "$IS_NIGHTLY" = "true" ]; then
ARGS+=(--config src-tauri/tauri.nightly.conf.json)
export SABLE_BUILD_FLAVOR=dev
fi
pnpm tauri ios build --no-sign --ci "${ARGS[@]}"
pnpm tauri ios build --no-sign --ci
IPA=$(find src-tauri/gen/apple/build -name '*.ipa' -type f | head -1)
[ -n "$IPA" ] || { echo "IPA not found"; ls -R src-tauri/gen/apple/build 2>/dev/null || true; exit 1; }
NORMALIZED_IPA="$(dirname "$IPA")/Sable-${VERSION}-ios-arm64.ipa"
@@ -556,7 +528,8 @@ jobs:
TAG: ${{ needs.setup-release.outputs.tag }}
VERSION: ${{ needs.setup-release.outputs.version }}
VITE_APP_VERSION: ${{ needs.setup-release.outputs.version }}
VITE_IS_RELEASE_TAG: ${{ needs.setup-release.outputs.nightly == 'true' && 'true' || '' }}
SABLE_BUILD_FLAVOR: ${{ needs.setup-release.outputs.nightly == 'true' && 'dev' || 'stable' }}
SABLE_PRODUCT_NAME: ${{ needs.setup-release.outputs.product_name }}
REPO: ${{ github.repository }}
STARTED_AT: ${{ needs.setup-release.outputs.started_at }}
steps:
+2 -2
View File
@@ -11,9 +11,9 @@ FROM base AS builder
WORKDIR /src
ARG VITE_BUILD_HASH
ARG VITE_IS_RELEASE_TAG=false
ARG SABLE_BUILD_FLAVOR=stable
ENV VITE_BUILD_HASH=$VITE_BUILD_HASH
ENV VITE_IS_RELEASE_TAG=$VITE_IS_RELEASE_TAG
ENV SABLE_BUILD_FLAVOR=$SABLE_BUILD_FLAVOR
COPY pnpm-lock.yaml pnpm-workspace.yaml /src/
RUN pnpm fetch
COPY . /src/
+1
View File
@@ -1,4 +1,5 @@
{
"productName": "Sable",
"defaultHomeserver": 0,
"homeserverList": ["matrix.org", "mozilla.org", "unredacted.org", "sable.moe", "kendama.moe"],
"allowCustomHomeservers": true,
+1 -1
View File
@@ -240,7 +240,7 @@
nativeBuildInputs = pnpmNativeBuildInputs;
env.VITE_BUILD_HASH = self.shortRev or self.dirtyShortRev or "";
env.VITE_IS_RELEASE_TAG = "false";
env.SABLE_BUILD_FLAVOR = "stable";
buildPhase = ''
runHook preBuild
+1
View File
@@ -14,6 +14,7 @@ name = "app_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
serde_json = "1.0"
tauri-build = { version = "2.6.3", features = [] }
tauri-typegen = "0.5"
+27
View File
@@ -14,6 +14,33 @@ fn main() {
println!("cargo:rerun-if-env-changed=VITE_SENTRY_ENVIRONMENT");
println!("cargo:rerun-if-env-changed=VITE_APP_VERSION");
let config_path = std::path::Path::new("../config.json");
let base = std::fs::read_to_string(config_path)
.ok()
.and_then(|content| serde_json::from_str::<serde_json::Value>(&content).ok())
.and_then(|config| {
config
.get("productName")
.and_then(|v| v.as_str())
.map(String::from)
})
.unwrap_or_else(|| "Sable".into());
let full_name = if matches!(
std::env::var("SABLE_BUILD_FLAVOR").ok().as_deref(),
Some("dev" | "nightly")
) {
format!("{} Nightly", base)
} else {
base
};
println!("cargo:rustc-env=SABLE_PRODUCT_NAME={}", full_name);
println!(
"cargo:rustc-env=TAURI_CONFIG={{\"productName\":\"{}\"}}",
full_name
);
println!("cargo:rerun-if-env-changed=SABLE_BUILD_FLAVOR");
// Find libcef.so next to the binary (CEF ships it there).
if std::env::var_os("CARGO_FEATURE_CEF").is_some()
&& std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("linux")
-4
View File
@@ -1,4 +0,0 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "Sable Nightly"
}
@@ -1,7 +1,7 @@
import type { ChangeEventHandler } from 'react';
import { useRef } from 'react';
import { Input, Chip, Text } from 'folds';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import { ArrowRight, sizedIcon, MagnifyingGlass } from '$components/icons/phosphor';
import { EmojiBoardTab } from '../types';
@@ -56,7 +56,7 @@ export function SearchInput({
)
}
onChange={onChange}
autoFocus={!mobileOrTablet()}
autoFocus={!isMobileOrTablet()}
/>
);
}
+5 -10
View File
@@ -1,5 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { getVersion } from '@tauri-apps/api/app';
import { isTauri } from '@tauri-apps/api/core';
import { getCurrentWindow, type Window } from '@tauri-apps/api/window';
import { listen } from '@tauri-apps/api/event';
@@ -112,9 +111,13 @@ export function DesktopTitleBar() {
}
}, [isWindows]);
const title = SABLE_PRODUCT_NAME;
useEffect(() => {
if (!isDesktopTitleBar) return undefined;
setWindowTitle(title);
const appWindow = getCurrentWindow();
appWindowRef.current = appWindow;
@@ -122,14 +125,6 @@ export function DesktopTitleBar() {
let unlistenResize: (() => void) | undefined;
let unlistenTracking: (() => void) | undefined;
getVersion()
.then((version) => {
if (mounted) setWindowTitle(version.includes('-nightly.') ? 'Sable Nightly' : 'Sable');
})
.catch((error) => {
log.warn('Failed to read app version for window title:', error);
});
const syncMaximized = async () => {
try {
const isMaximizedState = await appWindow.isMaximized();
@@ -182,7 +177,7 @@ export function DesktopTitleBar() {
unlistenResize?.();
unlistenTracking?.();
};
}, [isDesktopTitleBar, isWindows, hideSnapOverlay]);
}, [isDesktopTitleBar, isWindows, hideSnapOverlay, title]);
if (!isDesktopTitleBar) return null;
@@ -29,7 +29,7 @@ import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { UseStateProvider } from '$components/UseStateProvider';
import { EmojiBoard } from '$components/emoji-board';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import * as css from './UploadDescriptionEditor.css';
type DescriptionEditorProps = {
@@ -214,7 +214,7 @@ export function DescriptionEditor({
requestClose={() =>
setAnchor((v) => {
if (v) {
if (!mobileOrTablet()) ReactEditor.focus(editor);
if (!isMobileOrTablet()) ReactEditor.focus(editor);
return undefined;
}
return v;
+2 -2
View File
@@ -9,7 +9,7 @@ import { ScreenSize, useScreenSizeContext } from '../../hooks/useScreenSize';
import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import { useState, useEffect } from 'react';
export function CallChatView() {
@@ -34,7 +34,7 @@ export function CallChatView() {
flexGrow: 0,
}}
>
{!mobileOrTablet() && (
{!isMobileOrTablet() && (
<SidebarResizer
setCurWidth={setCurWidth}
sidebarWidth={vcmsgSidebarWidth}
+9 -9
View File
@@ -116,7 +116,7 @@ import { getEditedEvent, getMentionContent, getThreadReplyEvents } from '$utils/
import { buildReplacementContent } from './buildReplacementContent';
import { htmlToMarkdown } from '$plugins/markdown';
import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '$hooks/useCommands';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import { Reply, ThreadIndicator } from '$components/message';
import { roomToParentsAtom } from '$state/room/roomToParents';
import { nicknamesAtom } from '$state/nicknames';
@@ -429,7 +429,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setUploadBoard(true);
const safeFiles = await Promise.all(files.map(safeUploadFile));
// Eager-read to avoid Android content URI expiry after SAF picker
const blobbedFiles = mobileOrTablet()
const blobbedFiles = isMobileOrTablet()
? await Promise.all(
safeFiles.map(async (f) => {
try {
@@ -2034,7 +2034,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
}
before={
<>
{mobileOrTablet() ? (
{isMobileOrTablet() ? (
<>
<IconButton
onClick={() => setShowAttachmentSheet(true)}
@@ -2176,7 +2176,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
onTabChange={setEmojiBoardTab}
imagePackRooms={imagePackRooms}
returnFocusOnDeactivate={false}
isFullWidth={mobileOrTablet()}
isFullWidth={isMobileOrTablet()}
onEmojiSelect={handleEmoticonSelect}
onCustomEmojiSelect={handleEmoticonSelect}
onStickerSelect={handleStickerSelect}
@@ -2251,7 +2251,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
})}
</>
);
if (mobileOrTablet()) {
if (isMobileOrTablet()) {
return (
<>
{triggers}
@@ -2342,7 +2342,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
return;
}
if (!editorMicButton) return;
if (mobileOrTablet()) return;
if (isMobileOrTablet()) return;
setShowAudioRecorder(true);
}}
onMouseDown={(e: MouseEvent) => {
@@ -2352,7 +2352,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
if (showAudioRecorder) return;
if (hasContent) {
isLongPress.current = false;
if (mobileOrTablet() && delayedEventsSupported) {
if (isMobileOrTablet() && delayedEventsSupported) {
longPressTimer.current = setTimeout(() => {
isLongPress.current = true;
setShowSchedulePicker(true);
@@ -2361,7 +2361,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
return;
}
if (!editorMicButton) return;
if (!mobileOrTablet()) return;
if (!isMobileOrTablet()) return;
micHoldStartRef.current = Date.now();
setShowAudioRecorder(true);
@@ -2467,7 +2467,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
</FocusTrap>
}
/>
{delayedEventsSupported && !mobileOrTablet() && (
{delayedEventsSupported && !isMobileOrTablet() && (
<IconButton
onClick={(evt: MouseEvent<HTMLButtonElement>) => {
setScheduleMenuAnchor(evt.currentTarget.getBoundingClientRect());
+2 -2
View File
@@ -45,7 +45,7 @@ import { RoomInput } from './RoomInput';
import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing';
import * as css from './ThreadDrawer.css';
import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
type ThreadDrawerProps = {
room: Room;
@@ -605,7 +605,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
width: overlay ? '100%' : toRem(curWidth),
}}
>
{!mobileOrTablet() && (
{!isMobileOrTablet() && (
<SidebarResizer
setCurWidth={setCurWidth}
sidebarWidth={threadSidebarWidth}
+3 -3
View File
@@ -22,7 +22,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
import { factoryEventSentBy } from '$utils/matrix';
import { Reaction, ReactionTooltipMsg } from '$components/message';
import { EmojiBoard } from '$components/emoji-board';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import { sizedIcon, Smiley } from '$components/icons/phosphor';
import { useRelations } from '$hooks/useRelations';
import { stopPropagation } from '$utils/keyboard';
@@ -134,7 +134,7 @@ export const Reactions = as<'div', ReactionsProps>(
imagePackRooms={imagePackRooms ?? []}
returnFocusOnDeactivate={false}
allowTextCustomEmoji
isFullWidth={mobileOrTablet()}
isFullWidth={isMobileOrTablet()}
onEmojiSelect={(key) => {
onReactionToggle(mEventId, key);
setEmojiBoardAnchor(undefined);
@@ -170,7 +170,7 @@ export const Reactions = as<'div', ReactionsProps>(
)}
</TooltipProvider>
);
if (mobileOrTablet()) {
if (isMobileOrTablet()) {
return (
<>
{trigger}
@@ -16,7 +16,7 @@ import {
} from '$hooks/usePerMessageProfile';
import { stopPropagation } from '$utils/keyboard';
import { mxcUrlToHttp } from '$utils/matrix.ts';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import FocusTrap from 'focus-trap-react';
import { nameInitials } from '$utils/common';
import {
@@ -203,7 +203,7 @@ export function PersonaPicker({
size="400"
placeholder="Search"
maxLength={50}
autoFocus={!mobileOrTablet()}
autoFocus={!isMobileOrTablet()}
onChange={filter}
before={menuIcon(MagnifyingGlass)}
/>
@@ -29,7 +29,7 @@ import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { UseStateProvider } from '$components/UseStateProvider';
import { EmojiBoard } from '$components/emoji-board';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import { SettingTile } from '$components/setting-tile';
import * as css from './BioEditor.css';
@@ -200,7 +200,7 @@ export function BioEditor({ value, isSaving, imagePackRooms, onSave }: BioEditor
requestClose={() =>
setAnchor((v) => {
if (v) {
if (!mobileOrTablet()) ReactEditor.focus(editor);
if (!isMobileOrTablet()) ReactEditor.focus(editor);
return undefined;
}
return v;
@@ -1,6 +1,5 @@
import { addPluginListener, invoke, isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import { isDesktopTauri } from '$utils/platform';
import { addPluginListener, invoke } from '@tauri-apps/api/core';
import { isDesktopTauri, isMobileTauri } from '$utils/platform';
export type NotificationPluginListener = {
unregister: () => Promise<void> | void;
};
@@ -135,10 +134,8 @@ async function ensureTauriNotificationPermission(): Promise<boolean> {
return permissionPromise;
}
export const isIosTauri = (): boolean => isTauri() && osType() === 'ios';
export const isAndroidTauri = (): boolean => isTauri() && osType() === 'android';
// Platforms where OS notifications go through the native plugin instead of web APIs.
export const isNativeNotificationTauri = (): boolean => isDesktopTauri() || isIosTauri();
export const isNativeNotificationTauri = (): boolean => isDesktopTauri() || isMobileTauri();
let nativeNotificationSeq = 1;
const nextNativeNotificationId = (): number => {
@@ -187,4 +184,4 @@ export async function sendNativeTauriNotification({
});
}
export { isDesktopTauri };
export { isDesktopTauri, isMobileTauri };
@@ -24,11 +24,7 @@ import {
} from './UnifiedPushMessageListener';
import { addPluginListener } from '@tauri-apps/api/core';
import type { PushTransportConfig } from './NotificationTransport';
import {
getTauriNotificationsApi,
isAndroidTauri,
isIosTauri,
} from './TauriNotificationsApiClient';
import { getTauriNotificationsApi, isMobileTauri } from './TauriNotificationsApiClient';
import {
resolvePushNotifyUrl,
withPushPayloadFormat,
@@ -460,7 +456,7 @@ async function postRoomNotification(
silent: isSilent,
autoCancel: true,
extra,
...(isAndroidTauri() || isIosTauri() ? { actionTypeId: 'sable-message' } : {}),
...(isMobileTauri() ? { actionTypeId: 'sable-message' } : {}),
inboxLines: inboxLines.length > 1 ? inboxLines : undefined,
largeBody: inboxLines.length > 1 ? undefined : latestBody,
});
+3 -3
View File
@@ -41,7 +41,7 @@ import * as css from './WidgetsDrawer.css';
import { IntegrationManager } from './IntegrationManager';
import { CustomStateEvent } from '$types/matrix/room';
import { SidebarResizer } from '$pages/client/sidebar/SidebarResizer';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
type WidgetsDrawerHeaderProps = {
activeWidget: RoomWidget | null;
@@ -268,10 +268,10 @@ export function WidgetsDrawer({ room }: WidgetsDrawerProps) {
direction="Column"
style={{
position: 'relative',
width: !mobileOrTablet() ? toRem(curWidth) : 'inherit',
width: !isMobileOrTablet() ? toRem(curWidth) : 'inherit',
}}
>
{!mobileOrTablet() && (
{!isMobileOrTablet() && (
<SidebarResizer
setCurWidth={setCurWidth}
sidebarWidth={widgetSidebarWidth}
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-24T20:34:03.668649098+00:00
* Generated at: 2026-07-26T18:31:24.509277800+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-24T20:34:03.669019877+00:00
* Generated at: 2026-07-26T18:31:24.510042400+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-24T20:34:03.669061467+00:00
* Generated at: 2026-07-26T18:31:24.510311700+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
+1 -1
View File
@@ -1,7 +1,7 @@
/**
* Auto-generated TypeScript bindings for Tauri commands
* Generated by tauri-typegen v0.5.0
* Generated at: 2026-07-24T20:34:03.668078359+00:00
* Generated at: 2026-07-26T18:31:24.507322700+00:00
* Generator: none
*
* Do not edit manually - regenerate using: cargo tauri-typegen generate
+2 -2
View File
@@ -7,7 +7,7 @@ import { useClientConfig } from './useClientConfig';
import { useSetting } from '../state/hooks/settings';
import { settingsAtom } from '../state/settings';
import { pushSubscriptionAtom } from '../state/pushSubscription';
import { mobileOrTablet } from '../utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
import { createDebugLogger } from '../utils/debugLogger';
const debugLog = createDebugLogger('AppVisibility');
@@ -16,7 +16,7 @@ export function useAppVisibility(mx: MatrixClient | undefined) {
const clientConfig = useClientConfig();
const [usePushNotifications] = useSetting(settingsAtom, 'usePushNotifications');
const pushSubAtom = useAtom(pushSubscriptionAtom);
const isMobile = mobileOrTablet();
const isMobile = isMobileOrTablet();
useEffect(() => {
const handleVisibilityChange = () => {
+2 -1
View File
@@ -1,4 +1,5 @@
import { Box, Text } from 'folds';
import { versionLabel } from '$utils/platform';
import * as css from './styles.css';
export function AuthFooter() {
@@ -14,7 +15,7 @@ export function AuthFooter() {
target="_blank"
rel="noreferrer"
>
{`v${APP_VERSION}${IS_RELEASE_TAG ? '' : `-dev${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`}`}
{versionLabel()}
</Text>
<Text as="a" size="T300" href="https://matrix.org" target="_blank" rel="noreferrer">
Powered by Matrix
-6
View File
@@ -10,12 +10,6 @@ const getAppBaseUrl = (): string => {
return `${TAURI_SSO_PROTOCOL}//${TAURI_SSO_HOST}`;
}
if (import.meta.env.DEV) {
// TODO: disabled for now since it causes issues with the SSO flow. We should find a better solution for this in the future.
// return window.location.origin;
return `${TAURI_SSO_PROTOCOL}//${TAURI_SSO_HOST}`;
}
return `${TAURI_SSO_PROTOCOL}//${TAURI_SSO_HOST}`;
};
@@ -30,7 +30,7 @@ import { PasswordInput } from '$components/password-input';
import { getResetPasswordPath } from '$pages/pathUtils';
import { stopPropagation } from '$utils/keyboard';
import { FieldError } from '$pages/auth/FiledError';
import { deviceDisplayName } from '$utils/user-agent';
import { deviceDisplayName } from '$utils/platform';
import { getMxIdServer } from '$utils/mxIdHelper';
import type { CustomLoginResponse } from './loginUtil';
import { LoginError, factoryGetBaseUrl, login, useLoginComplete } from './loginUtil';
+1 -1
View File
@@ -4,7 +4,7 @@ import { useCallback, useEffect } from 'react';
import type { MatrixError } from '$types/matrix-sdk';
import { useAutoDiscoveryInfo } from '$hooks/useAutoDiscoveryInfo';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { deviceDisplayName } from '$utils/user-agent';
import { deviceDisplayName } from '$utils/platform';
import type { CustomLoginResponse } from './loginUtil';
import { LoginError, login, useLoginComplete } from './loginUtil';
@@ -37,7 +37,7 @@ import { ConfirmPasswordMatch } from '$components/ConfirmPasswordMatch';
import { UIAFlowOverlay } from '$components/UIAFlowOverlay';
import type { RequestEmailTokenCallback, RequestEmailTokenResponse } from '$hooks/types';
import { FieldError } from '$pages/auth/FiledError';
import { deviceDisplayName } from '$utils/user-agent';
import { deviceDisplayName } from '$utils/platform';
import { fetch } from '$utils/fetch';
import type { RegisterResult } from './registerUtil';
import { RegisterError, register, useRegisterComplete } from './registerUtil';
@@ -44,7 +44,7 @@ import * as Sentry from '@sentry/react';
import { startClient, stopClient } from '$client/initMatrix';
import { createSessionTokenRefresher } from '$client/oidcTokenRefresher';
import { isDesktopTauri } from '$utils/platform';
import { mobileOrTablet } from '$utils/user-agent';
import { isMobileOrTablet } from '$utils/platform';
const log = createLogger('BackgroundNotifications');
const debugLog = createDebugLogger('BackgroundNotifications');
@@ -511,7 +511,7 @@ export function BackgroundNotifications() {
// Show in-app banner when app is visible, mobile, and in-app notifications enabled
const canShowInAppBanner =
document.visibilityState === 'visible' &&
mobileOrTablet() &&
isMobileOrTablet() &&
showNotificationsRef.current;
if (canShowInAppBanner) {
+2 -1
View File
@@ -1,6 +1,7 @@
import { Box, Button, Text, config, toRem } from 'folds';
import { Code, Heart, menuIcon } from '$components/icons/phosphor';
import { Page, PageHero, PageHeroSection } from '$components/page';
import { versionLabel } from '$utils/platform';
import LogoSVG from '$public/res/svg/logo.svg';
export function WelcomePage() {
@@ -24,7 +25,7 @@ export function WelcomePage() {
target="_blank"
rel="noreferrer noopener"
>
{`v${APP_VERSION}${IS_RELEASE_TAG ? '' : `-dev${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`}`}
{versionLabel()}
</a>
</span>
}
+9 -8
View File
@@ -1,6 +1,7 @@
import { atom, type WritableAtom } from 'jotai';
import type { Store } from 'jotai/vanilla/store';
import { mobileOrTablet } from '$utils/user-agent';
import { isNightly } from '$utils/platform';
import { isMobileOrTablet } from '$utils/platform';
import type {
NotificationTransportMode,
NotificationTransportProvider,
@@ -298,7 +299,7 @@ export const defaultSettings: Settings = {
isPeopleDrawer: true,
isWidgetDrawer: false,
memberSortFilterIndex: 0,
enterForNewline: mobileOrTablet(),
enterForNewline: isMobileOrTablet(),
editorToolbar: false,
editorOldAddFile: false,
editorMicButton: true,
@@ -338,10 +339,10 @@ export const defaultSettings: Settings = {
// Push notifications (SW/Sygnal): default on for mobile, opt-in on desktop.
// In-app pill banner: default on for mobile (primary foreground alert), opt-in on desktop.
// System (OS) notifications: desktop-only; hidden and disabled on mobile.
usePushNotifications: mobileOrTablet(),
usePushNotifications: isMobileOrTablet(),
useUnifiedPush: false,
useInAppNotifications: mobileOrTablet(),
useSystemNotifications: !mobileOrTablet(),
useInAppNotifications: isMobileOrTablet(),
useSystemNotifications: !isMobileOrTablet(),
isNotificationSounds: true,
backgroundNotificationSounds: true,
showMessageContentInNotifications: false,
@@ -349,7 +350,7 @@ export const defaultSettings: Settings = {
useRichPushPayloads: true,
pushNotifyUrlOverride: undefined,
clearNotificationsOnRead: false,
backgroundPushEnabled: mobileOrTablet(),
backgroundPushEnabled: isMobileOrTablet(),
backgroundPushProvider: null,
pushTransportMode: 'auto',
pushTransportOverride: {},
@@ -371,7 +372,7 @@ export const defaultSettings: Settings = {
privacyBlurEmotes: false,
showPronouns: true,
parsePronouns: true,
pronounPillMaxCount: mobileOrTablet() ? 1 : 3,
pronounPillMaxCount: isMobileOrTablet() ? 1 : 3,
pronounPillMaxLength: 16,
renderGlobalNameColors: true,
renderUserCards: 'both',
@@ -771,7 +772,7 @@ export function sanitizeSettingsDefaults(raw: unknown): Partial<Settings> {
}
}
if (import.meta.env.DEV && warnings.length > 0) {
if (isNightly() && warnings.length > 0) {
console.warn(
'[config.settingsDefaults] ignored unknown or invalid keys:',
[...new Set(warnings)].slice(0, 25).join(', ')
+2 -1
View File
@@ -6,6 +6,7 @@
*/
import * as Sentry from '@sentry/react';
import { versionLabel } from '$utils/platform';
import { sanitizeSentryPayload } from './sentryScrubbers';
export type LogLevel = 'debug' | 'info' | 'warn' | 'error';
@@ -292,7 +293,7 @@ class DebugLoggerService {
return JSON.stringify(
{
exportedAt: new Date().toISOString(),
build: `v${APP_VERSION}${BUILD_HASH ? ` (${BUILD_HASH})` : ''}`,
build: versionLabel({ includeNightly: false }),
logsCount: this.logs.length,
logs: this.logs.map((log) => ({
...log,
+101 -9
View File
@@ -1,20 +1,59 @@
import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import { UAParser } from 'ua-parser-js';
export const ua = new UAParser(window.navigator.userAgent).getResult();
let tauriOSResolved = false;
let tauriOSValue: string | undefined;
function getTauriOS(): string | undefined {
if (!tauriOSResolved) {
tauriOSResolved = true;
if (isTauri()) {
try {
tauriOSValue = osType();
} catch {
tauriOSValue = undefined;
}
}
}
return tauriOSValue;
}
const MOBILE_TAURI_OS = ['android', 'ios'] as const;
const DESKTOP_TAURI_OS = ['linux', 'macos', 'windows'] as const;
export function isMobileOrTablet(): boolean {
const tauriOS = getTauriOS();
if (tauriOS && (MOBILE_TAURI_OS as readonly string[]).includes(tauriOS)) return true;
const { os, device } = ua;
if (device.type === 'mobile' || device.type === 'tablet') return true;
if (os.name === 'Android' || os.name === 'iOS') return true;
return false;
}
export function isNightly(): boolean {
return SABLE_BUILD_FLAVOR === 'dev';
}
export function versionLabel(opts?: { includeNightly?: boolean }): string {
const dev = (opts?.includeNightly ?? true) && isNightly() ? '-dev' : '';
const hash = BUILD_HASH ? ` (${BUILD_HASH})` : '';
return `v${APP_VERSION}${dev}${hash}`;
}
export function hasServiceWorker(): boolean {
// Android WebViews (Tauri) do not support service workers.
return 'serviceWorker' in navigator && !isTauri();
}
export type DesktopTauriPlatform = 'linux' | 'macos' | 'windows';
const DESKTOP_TAURI_OS = new Set<DesktopTauriPlatform>(['linux', 'macos', 'windows']);
export type DesktopTauriPlatform = (typeof DESKTOP_TAURI_OS)[number];
export function getDesktopTauriPlatform(): DesktopTauriPlatform | undefined {
if (!isTauri()) return undefined;
const os = osType() as string;
return DESKTOP_TAURI_OS.has(os as DesktopTauriPlatform)
? (os as DesktopTauriPlatform)
const tauriOS = getTauriOS();
return (DESKTOP_TAURI_OS as readonly string[]).includes(tauriOS ?? '')
? (tauriOS as DesktopTauriPlatform)
: undefined;
}
@@ -22,11 +61,15 @@ export function isDesktopTauri(): boolean {
return getDesktopTauriPlatform() !== undefined;
}
export function isMobileTauri(): boolean {
const tauriOS = getTauriOS();
return tauriOS === 'ios' || tauriOS === 'android';
}
export function hasControllingServiceWorker(): boolean {
return hasServiceWorker() && navigator.serviceWorker.controller !== null;
}
// window.location.origin is "null" on Tauri (tauri:// is opaque per WHATWG).
export function getAppOrigin(): string {
if (
isTauri() ||
@@ -47,3 +90,52 @@ export function getWindowOrigin(): string {
? `${window.location.protocol}//${window.location.host}`
: window.location.origin;
}
type FormFactor = 'Web' | 'Desktop' | 'Mobile';
// Display names for every known Tauri OS value. Kept exhaustive (rather than relying on capitalize() as a silent fallback) so a new OS is a visible gap.
const TAURI_OS_DISPLAY_NAMES: Record<string, string> = {
linux: 'Linux',
macos: 'macOS',
windows: 'Windows',
android: 'Android',
ios: 'iOS',
};
function capitalize(s: string): string {
return s.charAt(0).toUpperCase() + s.slice(1);
}
function normalizeOSName(os: string): string {
return os === 'Mac OS' ? 'macOS' : os;
}
function variantLabel(): string {
return isNightly() ? ' (Nightly)' : '';
}
function formFactor(): FormFactor {
if (!isTauri()) return 'Web';
const tauriOS = getTauriOS();
if (tauriOS && (MOBILE_TAURI_OS as readonly string[]).includes(tauriOS)) return 'Mobile';
return 'Desktop';
}
function osSpec(): string {
if (!isTauri()) {
const browser = ua.browser.name;
const os = ua.os.name;
if (browser && os) return `${browser} for ${normalizeOSName(os)}`;
if (browser) return browser;
if (os) return normalizeOSName(os);
return 'Web';
}
const tauriOS = getTauriOS();
if (tauriOS) return TAURI_OS_DISPLAY_NAMES[tauriOS] ?? capitalize(tauriOS);
const os = ua.os.name;
return os ? normalizeOSName(os) : 'Desktop';
}
export function deviceDisplayName(): string {
return `${SABLE_PRODUCT_NAME} ${formFactor()}${variantLabel()} on ${osSpec()}`;
}
-48
View File
@@ -1,48 +0,0 @@
import { isTauri } from '@tauri-apps/api/core';
import { type as osType } from '@tauri-apps/plugin-os';
import { UAParser } from 'ua-parser-js';
const result = new UAParser(window.navigator.userAgent).getResult();
const isMobileOrTablet = (() => {
if (isTauri()) {
try {
const tauriOs = osType();
if (tauriOs === 'android' || tauriOs === 'ios') return true;
} catch {
// Fallback to UA parsing if plugin-os is not ready/available
}
}
const { os, device } = result;
if (device.type === 'mobile' || device.type === 'tablet') return true;
if (os.name === 'Android' || os.name === 'iOS') return true;
return false;
})();
const normalizeMacName = (os?: string) => {
if (!os) return os;
if (os === 'Mac OS') return 'macOS';
return os;
};
const isMac = result.os.name === 'Mac OS' || result.os.name === 'macOS';
const isIosApp = (() => {
if (!isTauri()) return false;
try {
return osType() === 'ios';
} catch {
return false;
}
})();
export const isMacOS = () => isMac;
export const iosApp = () => isIosApp;
export const mobileOrTablet = () => isMobileOrTablet;
export const deviceDisplayName = (): string => {
const browser = result.browser.name;
const os = normalizeMacName(result.os.name);
if (!browser || !os) return 'Sable Web';
return `Sable on ${browser} for ${os}`;
};
+2 -1
View File
@@ -1,8 +1,9 @@
/// <reference types="vite/client" />
declare const SABLE_PRODUCT_NAME: string;
declare const SABLE_BUILD_FLAVOR: string;
declare const APP_VERSION: string;
declare const BUILD_HASH: string;
declare const IS_RELEASE_TAG: boolean;
declare module 'browser-encrypt-attachment' {
export interface EncryptedAttachmentInfo {
+14 -13
View File
@@ -19,6 +19,10 @@ import { createRequire } from 'module';
import { sentryVitePlugin } from '@sentry/vite-plugin';
import buildConfig from './build.config';
const appConfig = JSON.parse(
fs.readFileSync(path.resolve(__dirname, 'config.json'), 'utf8')
) as Record<string, unknown>;
const packageJson = JSON.parse(
fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf8')
) as {
@@ -57,16 +61,7 @@ const sentryUploadEnabled = Boolean(
process.env.SENTRY_AUTH_TOKEN && process.env.SENTRY_ORG && process.env.SENTRY_PROJECT
);
const isReleaseTag = (() => {
const envVal = process.env.VITE_IS_RELEASE_TAG;
if (envVal !== undefined && envVal !== '') return envVal === 'true';
try {
const tag = execSync('git describe --exact-match --tags HEAD 2>/dev/null').toString().trim();
return tag.startsWith('v');
} catch {
return false;
}
})();
const baseProductName = typeof appConfig.productName === 'string' ? appConfig.productName : 'Sable';
const copyFiles = {
targets: [
@@ -130,7 +125,11 @@ function serverMatrixSdkCryptoWasm() {
};
}
export default defineConfig(({ command }) => ({
export default defineConfig(({ command }) => {
const buildFlavor = process.env.SABLE_BUILD_FLAVOR || (command === 'serve' ? 'dev' : 'stable');
const productName = buildFlavor !== 'stable' ? `${baseProductName} Nightly` : baseProductName;
return ({
clearScreen: false,
appType: 'spa',
publicDir: false,
@@ -139,7 +138,8 @@ export default defineConfig(({ command }) => ({
define: {
APP_VERSION: JSON.stringify(appVersion),
BUILD_HASH: JSON.stringify(buildHash ?? ''),
IS_RELEASE_TAG: JSON.stringify(isReleaseTag),
SABLE_PRODUCT_NAME: JSON.stringify(productName),
SABLE_BUILD_FLAVOR: JSON.stringify(buildFlavor),
},
resolve: {
alias: {
@@ -308,4 +308,5 @@ export default defineConfig(({ command }) => ({
},
},
},
}));
});
});
+2 -1
View File
@@ -31,9 +31,10 @@ export default defineConfig({
},
},
define: {
SABLE_PRODUCT_NAME: JSON.stringify('Sable'),
SABLE_BUILD_FLAVOR: JSON.stringify('stable'),
APP_VERSION: JSON.stringify('test'),
BUILD_HASH: JSON.stringify(''),
IS_RELEASE_TAG: JSON.stringify(false),
},
test: {
environment: 'jsdom',