TutuHai

TutuHai Mini-App Open Docs

SDK integration · Capability APIs · Cloud data · Authorization · Publishing

TutuHai mini-apps are lightweight apps that run inside TutuHai. Developers upload only a frontend code bundle, hosted by the platform; capabilities talk to TutuHai through the window.tt SDK, with no backend of your own (business data goes through TutuHai cloud data). SDK integration · capability APIs · cloud data · authorization · publishing — all on one page, with copy-and-run examples.

Build an applet in the console 7 categories · 27 topics · Click a title to expand
Contents · 27 topics

Getting started

Data capabilities

Conversations & multiplayer

Files & cloud drive

Cross-app interaction

UI · window · host

Reference

Getting started

Introduction

TutuHai mini-apps are lightweight apps that run inside TutuHai. Developers upload only a frontend code bundle, hosted by the platform; capabilities talk to TutuHai through the window.tt SDK, with no backend of your own (business data goes through TutuHai cloud data).

Isolation and security: mini-apps run in a sandboxed iframe on an isolated origin; the host's login session never enters the mini-app. Each call is issued a short-lived, restricted token by the host, and the backend re-validates by capability (scope).

Quick start
  1. In the Mini-App Console (/applets), click "New" to create a mini-app (name + unique slug).
  2. Write a single-file HTML (include the SDK, call capabilities via window.tt.*).
  3. Create a version → fill in requested capabilities → upload the code bundle (single-file HTML).
  4. Submit for review → admin approves → publish to production in one click.
  5. Users find/open it via "Discover" search, or you share a card / copy a link for direct access.
Packaging spec

Mini-apps support two upload forms: ① a single-file HTML bundle (self-contained, entry = root, simplest); ② a real framework build output zip (the dist/ from npm run build, with index.html + assets across multiple files — see "Framework build output"). The platform runs a spec check and optimization before upload.

Bundle structure (build output)

your-applet/            # dev directory (any structure: src, components, assets…)
├─ src/ …               # your source (React / Vue / Svelte / vanilla)
└─ dist/index.html      # ★build output: single-file HTML (← upload this)
                        #   inlined CSS/JS, or referencing whitelisted CDNs; self-contained, no server

The code bundle must satisfy (auto-checked on upload):

  • Entry: a single HTML file with <!doctype html> and a root <html>.
  • Mobile fit: must include <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">.
  • SDK: include <script src="/applet-sdk.js"> (the platform rewrites it to the host's absolute address).
  • Self-contained: inline CSS/JS; if you need external scripts, only the platform SDK + well-known framework CDNs (unpkg / jsdelivr / cdnjs / esm.sh) are allowed — arbitrary remote scripts are forbidden (security). Images and other media go through tt.uploadImage or a CDN.
  • Size: single-file HTML ≤ 1MB; multi-file zip ≤ 8MB total, ≤ 1MB per file, ≤ 100 files; uploaded images ≤ 4MB.
  • Data: no backend of your own — business data goes through tt.cloud cloud data / tt.*storage.

📱🖥 Mobile / desktop universal (one codebase, both surfaces)

The same bundle runs in an isolated iframe inside TutuHai; the host carries it on both mobile (fullscreen) and desktop (panel / can go fullscreen). Write one universal codebase with a responsive layout: ① viewport-fit=cover + safe areas env(safe-area-inset-*); ② overlays as bottom sheets (mobile) ↔ centered (desktop, @media(min-width:480px)); ③ touch targets ≥ 44px; ④ follow the host's dark/light (tt.onThemeChange / [data-theme]); ⑤ pure DOM, no hard-coded widths. This keeps the experience consistent on both phone and computer.

Framework build output (dist.zip)

Besides single-file HTML, you can also upload a real framework's build output — use React / Vue / Svelte / Angular / Solid / Astro / Next (static export) / vanilla… any toolchain's npm run build, zip up the dist/ (with index.html + assets/*.js/css + fonts/images) and upload it to be hosted.

Framework-agnostic: the platform only recognizes one "universal static bundle contract" — entry index.html + relative asset references + SDK. Any framework that can produce a static dist meeting that contract is supported; the scaffolds below are just curated shortcuts, not the limit of support.

zip structure (build output, zip root = bundle root)

myapp.zip
├─ index.html          # ★entry (zip root)
├─ manifest.json       # declares slug/name/version/scopes (see below)
└─ assets/
   ├─ index-*.js       # built JS (relative references)
   ├─ index-*.css
   └─ font/img…

Three-step adaptation (works for any framework):

  1. Set a relative base (recommended, safest) — make the output reference assets by relative path (./assets/x.js rather than the root-absolute /assets/x.js), so hosting under /<slug>/ is foolproof. (The default base also works: the platform auto-rewrites root-absolute static references in HTML/CSS and uses a Referer fallback for root-absolute assets generated at runtime — such as preloads of code-split CSS; but under strict Referrer-Policy / offline-prefetch edge cases the Referer may be missing and the fallback fails, so a relative base is safest.)
  2. Add a manifest — put manifest.json in the static directory (e.g. Vite/SvelteKit's static/, most frameworks' public/) so it lands at the dist root after build; or omit the manifest and add <meta name="tt:slug" content="…"> (plus tt:name / tt:version / tt:scopes) in index.html as a fallback.
  3. Include the SDK — two ways: ① npm install (recommended, best for real scaffolds): after npm i @tutuhai/applet-sdk, import { tt } from '@tutuhai/applet-sdk' — bundled into the output at build time, with TypeScript types, no index.html edits; ② or write <script src="/applet-sdk.js"> in index.html (the platform rewrites it to the host's absolute address) and use the global window.tt.

📦 npm SDK (tested with React / Vue / Svelte official scaffolds)

Create a project with npm create vite@latest -- --template react-ts | vue-ts | svelte-ts, install the same @tutuhai/applet-sdk, and import it — real multi-file source, npm run build produces multiple chunks + one entry index.html; zip it up and upload.

# 1) Create a project with an official scaffold
npm create vite@latest my-applet -- --template react-ts   # or vue-ts / svelte-ts

# 2) Install the SDK (same package for all three frameworks)
npm i @tutuhai/applet-sdk

# 3) import and use in your source (typed)
#    src/App.tsx / App.vue / App.svelte
import { tt } from '@tutuhai/applet-sdk';
tt.ready((ctx) => {
  tt.getProfile().then((me) => console.log('hi', me?.nickname));
});
await tt.cloud.add('notes', { text: 'hello' });   // cloud data, no backend of your own

# 4) vite.config: relative base; public/manifest.json declares slug/name/scopes
#    export default { base: './', plugins: [react()] }

# 5) official build → zip dist → upload
npm run build && cd dist && zip -r ../my-applet.zip .

Runnable examples in the repo: applets/frameworks/{react,vue,svelte} (three real official-scaffold projects, all importing the same SDK package). SDK package source: applet-sdk/.

manifest.json fields

{
  "slug": "myapp",              // ★required, globally unique, determines hosting path /myapp/
  "name": "My Mini-App",        // ★required, display name
  "version": "1.0.0",           // ★required, must increment on every upload
  "scopes": ["user.profile"],   // requested capabilities (see "Authorization model")
  "description": "One-line summary",  // optional, shown on discover/detail
  "icon": "icon.png",           // optional, relative path in the bundle (or change it in the console after upload)
  "display": "fullscreen",      // optional, default open mode: window (floating, default) | fullscreen
  "fileHandlers": [             // optional, declares "Open with" — which file kinds you can handle from a chat
    { "kinds": ["image"], "role": "editor", "label": "TutuEdit · Retouch" }
  ]
}
  • display: declares the desktop open form — for canvas/whiteboard/editor apps prefer fullscreen, for lightweight cards/forms use the default window. It's only an initial value; after publishing you can change "Open mode" anytime in the console (the console wins). Mobile is always fullscreen, unaffected by this field. When the manifest is omitted, <meta name="tt:display" content="fullscreen"> works as a fallback.
  • fileHandlers: declares which file kinds your mini-app can handle from a chat — when a user taps "Open with" on a file in chat, mini-apps that declared a matching type appear as candidates; tapping one sends that file straight into your mini-app (see "Handling chat files"). Each item: kinds is one of image / video / audio / pdf / office / text / any (multiple allowed, any = any file); role is editor (open in an editor) or viewer (preview); label optional (≤20 chars, the candidate's display name). Up to 8 items. Gating matches visibility: private/self-use works without review (appears only in your own "Open with"); public requires admin approval before it takes effect for everyone.

One-line "relative base" config per framework:

// Vite (React/Vue/Svelte/Solid/Preact/Lit…)
export default { base: './' }
// SvelteKit (client-side routing → base must = slug) — static export + base set to your slug (else routes 404)
import adapter from '@sveltejs/adapter-static';
export default { kit: {
  adapter: adapter({ fallback: 'index.html' }),
  paths: { base: '/your-slug', relative: true }
} };
// Astro — astro.config.mjs
export default { base: './', build: { assets: 'assets' } }
# Angular — set a relative base href at build time
ng build --base-href ./ --output-path dist
// Next.js (static export) — next.config.js
module.exports = { output: 'export', images: { unoptimized: true }, assetPrefix: './' }
// Nuxt 3 (static) — nuxt.config.ts
export default defineNuxtConfig({ app: { baseURL: './', cdnURL: './' }, ssr: false })
// Vue CLI / webpack — vue.config.js (or webpack output.publicPath)
module.exports = { publicPath: './' }
<!-- Vanilla / no build: just use relative paths -->
<script src="./app.js"></script>
<link rel="stylesheet" href="./style.css">

⚠ Client-side-routed SPAs (SvelteKit / React Router / Vue Router / Angular) Mini-apps are hosted under the /<slug>/ subpath. A client-side-routed SPA must set its "router base" to your slug, otherwise the framework's router can't match the current path → whole-page 404 (assets load, but routing reports not found). Setting only a relative asset base is not enough — that only fixes asset URLs, not routing. Per framework: SvelteKit kit.paths.base='/<slug>'; React Router <BrowserRouter basename="/<slug>">; Vue Router createWebHistory('/<slug>/'); Angular APP_BASE_HREF='/<slug>/'. (Apps without client-side routing — pure rendering / a single-page React without Router / vanilla — are unaffected.)

⚠ Upload check-up On upload the platform runs a "contract check-up" on the dist: entry / relative paths / manifest / SDK reference / limits / MIME are each validated with inline hints. Total ≤ 8MB, ≤ 1MB per file, ≤ 100 files, whitelisted MIME only (html/css/js/json/images/fonts/map/wasm). Compress and subset fonts to keep size down. For heavyweight framework outputs (e.g. tldraw / excalidraw with a >1MB single chunk) that exceed the default per-file/total limits, ask the operations team to raise the "per-file bytes" / "unpacked total" limits in the admin panel (changeable at runtime, effective immediately); splitting manualChunks can also bring vendor under the limit.

Minimal example

A complete, runnable mini-app — include the SDK, read the user's nickname:

<!doctype html>
<html>
  <body>
    <div id="who">Loading…</div>
    <!-- Relative path — maintenance-free: survives domain changes/blocks (platform rewrites to the host's absolute URL) -->
    <script src="/applet-sdk.js"></script>
    <script>
      window.tt.ready(function () {
        window.tt.getProfile().then(function (me) {
          document.getElementById('who').textContent = 'Hi, ' + me.nickname;
        });
      });
    </script>
  </body>
</html>
SDK integration

Include the SDK script in your mini-app HTML, then use window.tt:

<!-- Include the SDK in your mini-app HTML. Use a relative path — don't hardcode a domain -->
<script src="/applet-sdk.js"></script>

Never hardcode the host domain into your mini-app. Write the relative /applet-sdk.js (or any placeholder origin) — the platform rewrites the SDK script URL to the current host at serve time when your app runs in its iframe. So even if TutuHai changes its domain, or a domain gets blocked, every published mini-app keeps working with no code change and no re-publish — an operator flips a single config value.

Ready callback, context, and theme/locale:

// After ready you get the context (appId / granted scopes / deep-link path / query / theme / locale / whether inline)
window.tt.ready(function (ctx) {
  console.log(ctx.appId, ctx.scopes, ctx.path, ctx.query, ctx.theme, ctx.colorScheme, ctx.locale, ctx.inline);
});
window.tt.context();   // get the current context snapshot anytime (same as ready's ctx)

// Theme switching (fires live when the host toggles light/dark)
window.tt.onThemeChange(function (theme) {
  document.documentElement.setAttribute('data-theme', theme);
});

// Locale switching (synced with the host's i18n; fires live when the host changes language — same mechanism as theme)
window.tt.onLocaleChange(function (locale) {   // e.g. 'zh-CN' / 'en-US'
  document.documentElement.setAttribute('lang', locale);  // the SDK sets it already; you can also localize your own copy
});
Framework examples

window.tt is framework-agnostic and works directly in all mainstream frameworks (single-file, no build). Each example includes both success ✅ and failure ❌ (authorization denied / network error) handling:

Vanilla JS

// No framework — vanilla DOM
window.tt.ready(function () {
  window.tt.getProfile()
    .then(function (me) {              // ✅ success
      document.getElementById('who').textContent = 'Hi, ' + me.nickname;
    })
    .catch(function (err) {            // ❌ failure (user denied authorization / network error)
      document.getElementById('who').textContent = 'Failed: ' + err.message;
    });
});

React

// React 18 + htm (no build)
const { useState, useEffect } = React;
function App() {
  const [me, setMe] = useState(null);
  const [err, setErr] = useState('');
  useEffect(() => {
    window.tt.ready(() =>
      window.tt.getProfile().then(setMe).catch((e) => setErr(e.message))
    );
  }, []);
  if (err) return html`<div>Failed: ${err}</div>`;      // ❌
  return html`<div>Hi ${me ? me.nickname : '…'}</div>`;  // ✅
}

Preact

// Preact + htm (no build)
const { useState, useEffect } = preactHooks;
function App() {
  const [me, setMe] = useState(null), [err, setErr] = useState('');
  useEffect(() => {
    window.tt.ready(() =>
      window.tt.getProfile().then(setMe).catch((e) => setErr(e.message))
    );
  }, []);
  return html`<div>${err ? 'Failed: ' + err : 'Hi ' + (me ? me.nickname : '…')}</div>`;
}

Vue 3

// Vue 3 (CDN)
const { createApp, ref, onMounted } = Vue;
createApp({
  setup() {
    const me = ref(null), err = ref('');
    onMounted(() => window.tt.ready(() =>
      window.tt.getProfile()
        .then((p) => (me.value = p))     // ✅
        .catch((e) => (err.value = e.message))  // ❌
    ));
    return { me, err };
  },
  template: `<div>{{ err ? 'Failed: ' + err : 'Hi ' + (me?.nickname ?? '…') }}</div>`
}).mount('#app');

Svelte

// Svelte (runtime compile)
let me = $state(null), err = $state('');
window.tt.ready(() =>
  window.tt.getProfile()
    .then((p) => (me = p))            // ✅
    .catch((e) => (err = e.message))  // ❌
);
// template: <div>{err ? 'Failed: ' + err : 'Hi ' + (me?.nickname ?? '…')}</div>

Solid

// SolidJS
import { createSignal, onMount } from 'solid-js';
function App() {
  const [me, setMe] = createSignal(null), [err, setErr] = createSignal('');
  onMount(() => window.tt.ready(() =>
    window.tt.getProfile().then(setMe).catch((e) => setErr(e.message))
  ));
  return <div>{err() ? 'Failed: ' + err() : 'Hi ' + (me()?.nickname ?? '…')}</div>;
}

Alpine.js

<!-- Alpine.js: declarative in HTML, zero build -->
<div x-data="{ me: null, err: '' }"
     x-init="window.tt.ready(() =>
       window.tt.getProfile()
         .then(p => me = p)              /* ✅ */
         .catch(e => err = e.message))"> <!-- ❌ -->
  <span x-text="err ? 'Failed: ' + err : 'Hi ' + (me?.nickname ?? '…')"></span>
</div>

Lit

// Lit (Web Components)
import { LitElement, html } from 'lit';
class MyApp extends LitElement {
  static properties = { me: {}, err: {} };
  connectedCallback() {
    super.connectedCallback();
    window.tt.ready(() =>
      window.tt.getProfile()
        .then((p) => (this.me = p))            // ✅
        .catch((e) => (this.err = e.message))  // ❌
    );
  }
  render() {
    return html`<div>${this.err ? 'Failed: ' + this.err : 'Hi ' + (this.me?.nickname ?? '…')}</div>`;
  }
}
customElements.define('my-app', MyApp);

jQuery

// jQuery
$(function () {
  window.tt.ready(function () {
    window.tt.getProfile()
      .then(function (me) { $('#who').text('Hi, ' + me.nickname); })      // ✅
      .catch(function (err) { $('#who').text('Failed: ' + err.message); }); // ❌
  });
});

Angular

// Angular (component)
@Component({ selector: 'app-root', template: `<div>{{ msg }}</div>` })
export class AppComponent implements OnInit {
  msg = 'Loading…';
  ngOnInit() {
    const tt = (window as any).tt;
    tt.ready(() =>
      tt.getProfile()
        .then((me: any) => (this.msg = 'Hi, ' + me.nickname))       // ✅
        .catch((e: any) => (this.msg = 'Failed: ' + e.message))     // ❌
    );
  }
}

Full runnable examples are in the repo: applet-platform/samples/demo-react.html, demo-svelte.html, demo-vue.html.

Data capabilities

User profile · user.profile
// Get the current user's profile (needs user.profile; on first call the host prompts for authorization as needed)
try {
  const me = await window.tt.getProfile();       // ✅ success
  console.log(me.userId, me.nickname, me.avatarUrl);
} catch (err) {                                   // ❌ failure
  // err.message: "User denied authorization" (tapped deny) / network error
  console.warn('Failed to get profile:', err.message);
}

// Profile changes (you or someone in the room changed nickname/avatar) → re-fetch and refresh display
window.tt.onProfileChange(() => refreshWhoUI());
Cloud data · cloud.data

Hosted structured collections that let a mini-app persist business data with no backend of its own. Three visibility tiers:

  • mine: read/write only your own documents (default).
  • all: read/write everything, only the mini-app developer (owner) — for a "merchant console" to see all orders/tickets.
  • public: any logged-in user can read everything, the collection name must start with pub_ — for community/marketplace/forum; writes and edits are still limited to the author.
// Cloud data: no backend of your own, business data hosted by the TutuHai platform. All calls return a Promise — always handle failure.
try {
  // Create a document (owned by the current user)
  const { id } = await window.tt.cloud.add('orders', { items: cart, total: 68, status: 'pending' });
  // Idempotent upsert: create or update by docKey (most common for "one vote per person" / one record per user, avoids fetch-id-then-update)
  await window.tt.cloud.put('votes', me.userId, { choice: 'A' });
  // My documents
  const mine = await window.tt.cloud.list('orders', { scope: 'mine' });
  // Read one (by id; returns null if not found)
  const doc = await window.tt.cloud.get('orders', id);
  // All documents (developer/owner only, for the merchant console; regular users → 403)
  const all = await window.tt.cloud.list('orders', { scope: 'all' });
  // Public collection: name starts with pub_ → any logged-in user can read everything (community/marketplace)
  const posts = await window.tt.cloud.list('pub_posts', { scope: 'public' });
  // where equality filter (server filters on a single data field; on large collections it narrows by parent key to avoid child docs being cut off by the 200 cap)
  const votes = await window.tt.cloud.list('pub_votes', { scope: 'public', where: { pollId: id } });
  // Beyond 200 rows: listPage cursor pagination (mine/all; can take where), returns { docs, nextCursor }
  const pg = await window.tt.cloud.listPage('orders', { scope: 'mine', limit: 100, before: cursor });
  // Field-level update (owner or developer; patch merges with the original data)
  await window.tt.cloud.update('orders', id, { status: 'done' });
  // Delete a document (owner or developer; idempotent) — completes CRUD, no need to pile up soft-delete flags
  await window.tt.cloud.delete('orders', id);
} catch (err) {                                   // ❌ failure
  // Insufficient permission (403) / using public on a non-pub_ collection (400) / quota exceeded / network
  console.warn('Cloud data error:', err.message);
}

Each row reads back like { id, ownerId, mine, data:{…your fields}, createdAt, updatedAt } — your fields are all in data (e.g. row.data.title).

KV storage · storage.kv

Key-value isolated per (mini-app, user), good for small private state like check-in counts, drafts, etc. tt.cloudStorage (setItem/getItem/getKeys/removeItem) is its Telegram-style alias.

// Hosted KV (needs storage.kv): isolated per (mini-app, user), stores private state
try {
  await window.tt.setStorage('count', 3);
  const n = await window.tt.getStorage('count'); // 3 (returns null if absent)
  await window.tt.removeStorage('count');
  const keys = await window.tt.getStorageKeys();
} catch (err) {                                   // ❌ quota (≤64 keys / 8KB) / network
  console.warn('Storage failed:', err.message);
}

// Telegram-style alias (same as above, needs storage.kv):
await window.tt.cloudStorage.setItem('draft', 'unsent content');
const draft = await window.tt.cloudStorage.getItem('draft');   // returns null if absent
const ks = await window.tt.cloudStorage.getKeys();
await window.tt.cloudStorage.removeItem('draft');

Conversations & multiplayer

Conversation capabilities · im.share / im.send / im.read / media.upload

All interaction with TutuHai conversations is mediated by the host (the user actively picks a conversation); mini-apps can't get the full conversation list. im.read is a sensitive capability.

// Conversation capabilities are all host-mediated (the user actively picks a conversation); always handle "user cancelled" and failure.
try {
  // Share this mini-app's card to a conversation (needs im.share; if no conversation is passed the host shows a picker)
  await window.tt.shareToChat({ title: 'Come vote for lunch 🍜' });
  // Send a text notification to a conversation (needs im.send; the host shows a picker + preview, signed "via the X mini-app")
  await window.tt.sendMessage('Vote result: Lanzhou beef noodles win');
  // Read conversation messages (needs im.read, sensitive; the user picks a conversation each time, non-text is redacted)
  const r = await window.tt.readMessages({ limit: 30 });
  // Upload an image (needs media.upload; pass a dataURL, returns an absolute URL)
  const url = await window.tt.uploadImage(dataUrl);
} catch (err) {                                   // ❌ failure
  // "User cancelled" (picker/preview cancelled) / authorization denied / "Call timed out" / network
  console.warn('Capability call failed:', err.message);
}
Multiplayer rooms · im.room

Turn a "conversation" into a realtime room for mini-games / collaboration: create/join a room, in-room persistent messages and realtime signals (state sync, ≤2KB, ephemeral, not persisted). The host bridges realtime frames as you, the host JWT never enters the mini-app; limited to rooms this mini-app created / conversations you were shared into — it can't touch the user's other private chats.

// Multiplayer rooms (needs im.room): create/join/leave + in-room persistent messages + realtime signals (≤2KB, ephemeral, not persisted).
const { conversationId } = await window.tt.room.create({ title: 'Gomoku match' }); // create room, host auto-subscribes
await window.tt.room.join(conversationId);                 // idempotent join; host auto-subscribes to realtime frames
await window.tt.room.subscribe(conversationId);            // subscribe to an existing conversation's realtime frames (e.g. a group you were shared into)
await window.tt.room.send(conversationId, 'Game on!');     // persistent text (visible even without opening the mini-app)
window.tt.room.signal(conversationId, { type:'move', cell:4 }); // send a realtime signal (state sync)
window.tt.room.setTyping(conversationId, true);            // typing state (transient)
const members = await window.tt.room.members(conversationId);   // roster [{userId,nickname,avatarUrl,online,isOwner}]
const past = await window.tt.room.history(conversationId, { limit: 50 }); // hydrate on reconnect (ascending)
await window.tt.room.leave(conversationId);                // leave (empty rooms are auto-reclaimed)

// Realtime events (all under tt.room):
window.tt.room.onMessage((m) => appendMsg(m));      // new message {conversationId,id,senderId,senderName,kind,text,createdAt}
window.tt.room.onSignal((s) => applyMove(s.payload));// opponent's realtime action {conversationId,senderId,payload}
window.tt.room.onPresence((p) => refreshOnline(p)); // online/offline {userId,online}
window.tt.room.onTyping((t) => showTyping(t));       // typing {conversationId,userId,typing}
window.tt.room.onMember(() => reloadMembers());      // member joined/left {conversationId} → re-fetch members()
window.tt.room.onReconnect(() => rehydrate());       // dropped & reconnected → re-hydrate current state from history()/cloud

Reconnect hydration: signals are best-effort and frame loss on disconnect is normal. On onReconnect, re-hydrate the final state from room.history() or cloud data — don't rely on signals as the single source of truth.

Inline components · native-component-like · privacy-safe

A card sent with shareToChat({inline:true}) renders an interactive component right inside the chat bubble (e.g. a poll, a rating); recipients operate it like a native feature without opening a floating window. The mini-app renders a compact UI based on ctx.inline; the bubble auto-sizes to content and re-themes live with the host's light/dark. Privacy: an inline instance gets only a "cloud.data only, no side effects" restricted token — it can read public collections + write its own documents, can't touch others' private data, and doesn't prompt for authorization.

// —— Inline components: make a mini-app interact right in the chat bubble like a native feature (polls/ratings/relays…) ——
// 1) Send an inline card to a conversation (needs im.share): recipients operate it in the bubble without opening the mini-app
await window.tt.shareToChat({ inline: true, query: { pollId }, title: 'Poll', height: 200 });

// 2) The mini-app renders two forms based on ctx.inline
window.tt.ready((ctx) => {
  if (ctx.inline) {
    renderCompact(ctx.query.pollId);   // inline: a compact "native-component-like" UI
    window.tt.reportHeight();          // report height (the SDK also auto-reports via ResizeObserver; the bubble auto-sizes to content)
    // When full functionality is needed, open the full page (floating/fullscreen) from the inline card:
    // openBtn.onclick = () => window.tt.openFullPage('/detail?pollId=' + ctx.query.pollId);
  } else {
    renderFull();                      // floating window: full creation UI
  }
});
// Privacy: an inline instance gets only a "cloud.data only, no side effects" restricted token — it can read public collections + write its own documents,
// can't touch others' private data; doesn't prompt for authorization or pollute the authorization list. Sensitive capabilities (upload/send/location) are unavailable inline.
// Dark/mobile: inline cards switch light/dark live with the host and auto-fit width — no extra work for the developer.
Embedded state · seamless embedding · auto height · tt.embedded / tt.surface / tt.chromeless

Besides running standalone, a mini-app can be embedded inline by a host: a chat inline card, or a site (the "Tutu App" block in TutuSite) that renders your mini-app as a block on a page. When embedded, the SDK tells you the embed state and automatically reports your real content height to the host — the host sizes the iframe to your content, so the host page scrolls and the iframe itself never shows a scrollbar, exactly like a native in-page component. You barely need to adapt.

Detect "am I embedded" + hide your header seamlessly:

  • JS: window.tt.embedded (embedded inline, alias of tt.inline), window.tt.surface (host surface — one of 'chat' / 'full' / 'store' / 'preview' / 'embed'), window.tt.chromeless (host wants your header hidden for a seamless look). Available after tt.ready.
  • Pure CSS (recommended, no JS) — the SDK adds classes to <html>:
    • .tt-embedded — when embedded. Hide shells only needed when standalone (back bar, big brand title…).
    • .tt-chromeless — host wants chromeless. Hide your own header with this.
    • .tt-surface-<name> (the name is the value of tt.surface, e.g. .tt-surface-embed) — tune density/spacing per surface.
.tt-embedded .standalone-only { display: none; }   /* e.g. back button, brand banner */
.tt-chromeless .app-header    { display: none; }    /* host wants chromeless → hide your header */
.tt-surface-embed .grid       { gap: 8px; }

Auto-height rules (must follow, or you'll get a scrollbar / clipping when embedded):

  • Do not lock the embedded root to height:100vh / height:100% + overflow. Let content flow and grow naturally so the SDK can measure the real height and the host can show it in full. For a fixed play area / internal scroll region, put overflow:auto on a child element (the SDK keeps your internal scroll areas intact) — never lock the root.
  • Give images width/height or aspect-ratio to avoid jumping after load (the SDK re-measures after images/fonts/video load and on window resize, but explicit sizes are steadier).
  • Height reports automatically; call window.tt.reportHeight() only if you really need to.

When running standalone (not embedded) there are no such classes and tt.embedded===false, so your header/shell shows normally — the same code works in both cases.

Word lookup / translate · text.lookup / text.provider

The word-lookup popover is itself the inline page of a "provider mini-app" — its content/functionality is all rendered by that mini-app; the host only provides the selection + hover positioning + a flexible SDK. Consumers (make text in your own mini-app selectable): declare text.lookup, zero code — selecting text pops the provider's inline page right below the selection (chat message text is supported too). Providers (build a lookup mini-app): declare text.provider (granted after review), the inline page receives words via tt.text.onLookup and renders itself; which provider is active is configured in the admin panel — if none is configured/authorized, lookup is disabled. Add data-tt-no-lookup to opt out of a region.

// ── A. Make "text inside your mini-app" selectable for lookup (consumer, needs text.lookup) ──【zero code】
// After declaring "text.lookup" in the manifest, when a user selects text in your mini-app, a popover
// 【the provider mini-app's inline page】pops up right below the selection (auto dictionary/translation). Chat message text is also supported (host built-in).
// Tap blank/scroll/Esc to hide; operating inside the popover doesn't close it. No JS needed.
// Opt out: add data-tt-no-lookup to regions you don't want selectable; <input type=password> is auto-excluded.

// ── B. Build a "word-lookup provider mini-app" (provider, needs text.provider, granted after review) ──
// The provider page (inline mode) receives the selected text pushed by the host via onLookup (pushed initially + on every new word, stays resident without reload),
// and looks up/translates/renders it into any UI; you can use tt.text.lookup to call the built-in engine, or your own cloud.data dictionary.
tt.ready(function () {
  tt.text.onLookup(function (text) {          // host pushes the selected text
    tt.text.lookup(text).then(function (r) {  // r={kind:'dict'|'translate',...}
      render(r);                              // render into your own UI (auto-height)
    });
  });
});

// ── Escape hatch / flexible SDK primitives (available to any mini-app) ──
const r = await window.tt.text.lookup('lazy', { to:'en' });        // look up / translate on demand
window.tt.text.onSelect(function (sel){ /* {text, rect}; registering takes over, the default popover steps aside */ });
window.tt.openFloating({ path:'/detail', anchor: sel.rect, width:320, height:220 }); // open a floating window at the selection
window.tt.floating.moveTo(100, 200);  // the floating window's position/size are fully adjustable via the SDK: setRect/moveTo/resize/close

Files & cloud drive

Handling chat files · media.upload / im.share

When a user taps "Open with" on an image/file in chat, they can pick your mini-app to handle it — provided you declared a matching file type in manifest.json's fileHandlers (image/video/audio/pdf/office/text/any). Once open: getContextFile() gets the file, readFile() fetches the bytes same-origin via the host (avoiding CORS, so you can analyze images/audio/video/any format), then after processing uploadFile() + sendFileToChat() sends it back to the conversation, or saveFile() downloads it — a seamless flow.

// —— Handling chat files: the user taps "Open with" on a file and picks your mini-app (must declare matching kinds in manifest.fileHandlers) ——
const f = window.tt.getContextFile();
// f = {url,name,mime,size,kind:'image'|'file',conversationId,messageId} or null (when opened standalone)
if (f) {
  const bytes = await window.tt.readFile(f.url);   // host fetches bytes same-origin (avoids iframe CORS; limited to this site's /uploads output)
  // bytes = {dataUrl, mime, name, size, url} — feed to <img>/<video>/<audio>/canvas to analyze any format
  imgEl.src = bytes.dataUrl;
}
// —— Process the output → send back to the conversation or download (needs media.upload / im.share) ——
const out = canvas.toDataURL('image/webp', 0.9);            // e.g. convert image to WebP
const up = await window.tt.uploadFile({ dataUrl: out, name: 'result.webp' });   // {url,name,size,mime} (≤20MB)
await window.tt.sendFileToChat({
  url: up.url, name: up.name, mime: up.mime, size: up.size,
  conversationId: f.conversationId    // pass it to send straight to the original conversation (skip the picker); omit it and the host shows a conversation picker
});
await window.tt.saveFile({ dataUrl: out, name: 'result.webp' });   // or: download locally (host downloads on your behalf)
Tutu Drive · tt.drive (needs media.upload)

Pick files in from Tutu Drive, or save your output into the drive (host-mediated: the user picks files one at a time in the drive picker inside the host page; the mini-app doesn't hold a drive token). Rejects when the drive is unreachable / the Tutu ID isn't federated — after .catch, the mini-app can fall back to a local uploadFile.

// Pick files from the drive (the user picks in the host's drive picker; returns [] on cancel):
const picked = await window.tt.drive.pick({ multiple: true, accept: 'image/*' });
// picked = [{ nodeId, name, size, mime, downloadUrl }]
for (const file of picked) {
  const bytes = await window.tt.readFile(file.downloadUrl);  // fetch bytes to analyze/display
  render(bytes.dataUrl);
}

// Save a file into the drive (pass this site's /uploads output absolutized as pullUrl, or a dataUrl directly):
const saved = await window.tt.drive.save({ pullUrl: up.url, name: 'export-result.png' });
// saved = { nodeId, name }

Cross-app interaction

Cross-app interaction · drag between apps · tt.link / tt.tray / tt.drag / tt.drop (no authorization needed)

Multiple mini-apps can be open at the same time (saved as a combo to open together in one click, multi-window 2/3/4 layouts, a docked sidebar — all managed by the host, no code needed), and interact via the following capabilities:

  • tt.link: sync events/state in realtime with other open mini-apps (broadcast or targeted, ≤2KB, rate-limited 25/s; drops on window close, not persisted, not cross-user/conversation).
  • tt.tray: pick content up into the host tray to relay it, then inject into another mini-app or conversation.
  • tt.drag.start / tt.drag.bind: start a drag / bind an element as a drag source that can be dragged straight into another mini-app (native HTML5 drag-and-drop between same-origin mini-apps).
  • tt.drop.accept: the whole mini-app can receive drops / tray injections.
  • tt.drop.zone: ★let a specific internal element sense a drop (with hover-highlight feedback) and act on it. A mini-app can have multiple zones, each sensing independently.

Security: a file-wrapped url only accepts this site's /uploads/ handles (the receiver fetches bytes via tt.readFile); forged cross-origin external links are dropped; text/json/name all have size caps.

// —— ① Event/state sync tt.link (broadcast in realtime with "other open mini-apps"; drops on window close, not persisted, not cross-user/conversation) ——
tt.link.send({ type: 'color', color: '#ef4444' });        // broadcast to all linked mini-apps (≤2KB, rate-limited 25/s)
tt.link.sendTo(appId, { type: 'ping' });                  // send to a specific peer
tt.link.on((from, msg) => { /* from={appId,slug,name} */ apply(msg); });
const peers = await tt.link.peers();                      // the other linked mini-apps right now [{appId,slug,name}]

// —— ② Tray relay tt.tray (pick up → drop into another mini-app / conversation) ——
await tt.tray.put({ kind:'json', name:'color', data:{ color:'#ef4444' } }); // put into the host tray
const items = await tt.tray.list();                       // view the tray [parcel]
const p = await tt.tray.take(id);                         // take a parcel out
// parcel = { kind:'file'|'text'|'json', url?/text?/data?, name?, mime? }

// —— ③ Direct drag between apps 【drag source】tt.drag ——
tt.drag.start({ kind:'json', name:'color', data:{ color:'#ef4444' } }); // start a drag, returns {id}
tt.drag.bind(swatchEl, () => ({ kind:'json', name:'color', data:{ type:'color', color:'#ef4444' } }));
// getParcel() returns this drag's parcel; return null to not start. Between same-origin mini-apps it uses native HTML5 drag-and-drop with the browser's built-in ghost.

// —— ④ Receive 【whole window】tt.drop.accept ——
tt.drop.accept(['json','file'], (parcel) => { apply(parcel); }); // callback on drop anywhere in this window / tray injection

// —— ⑤ ★Receive 【element-level】tt.drop.zone ——
tt.drop.zone(slotEl, ['json','file'], {
  onEnter: () => slotEl.classList.add('hot'),    // drag into this element → only it highlights (internal elements sense independently)
  onOver:  () => {},                             // while hovering (do continuous feedback)
  onLeave: () => slotEl.classList.remove('hot'), // move out → clear highlight
  onDrop:  (parcel) => fill(slotEl, parcel),     // dropped on this element → only it receives and acts
});

UI · window · host

UI · window · device (no authorization needed)

WeChat wx.*-like UI capabilities — the host renders real toasts/dialogs/image viewers, controls the mini-app's capsule window, and accesses clipboard/vibration/dialing/location/network — callable without requesting authorization, making a mini-app as powerful as a native app.

// —— Interaction feedback ——
window.tt.showToast({ title: 'Saved', icon: 'success' });   // icon: success|error|loading|none
window.tt.hideToast();
window.tt.showLoading({ title: 'Processing…' });            // pair with window.tt.hideLoading()
window.tt.hideLoading();
const { confirm } = await window.tt.showModal({ title: 'Confirm', content: 'Delete this?' });
const { tapIndex } = await window.tt.showActionSheet({ itemList: ['Camera', 'Album'] }); // rejects on cancel
// —— Window / system info ——
window.tt.setNavigationBarTitle({ title: 'My page' });      // change the mini-app capsule title
const info = await window.tt.getSystemInfo();               // {theme, platform, windowWidth, windowHeight, safeAreaInsets, appName, version}
// —— Device ——
await window.tt.setClipboardData({ data: 'copied text' });
const { data } = await window.tt.getClipboardData();
window.tt.vibrateShort();  window.tt.vibrateLong();          // haptic feedback
window.tt.makePhoneCall({ phoneNumber: '10086' });
// —— Media ——
window.tt.previewImage({ urls: [url1, url2], current: url1 }); // fullscreen image preview
// —— Location / external link / network ——
const loc = await window.tt.getLocation();                    // browser prompts for permission → {latitude, longitude, accuracy, speed}
window.tt.openLocation({ latitude: loc.latitude, longitude: loc.longitude, name: 'Store' }); // view on a map
window.tt.openLink({ url: 'https://example.com' });           // open in a new tab (http/https only)
const net = await window.tt.getNetworkType();                 // {isConnected, networkType: wifi|4g|...}
Floating window · fullscreen · branding

Control the mini-app window: open a draggable floating window from inline/a selection, expand to fullscreen / restore, tint the host capsule, and listen for show/size changes.

// —— Floating window (open a draggable floating window from inline / a selection) ——
window.tt.openFloating({ path:'/detail', anchor: rect, x:100, y:120, width:320, height:220 });
window.tt.floating.setRect({ x, y, width, height });  // also moveTo(x,y) / resize(w,h) / close()
window.tt.openFullPage('/detail');                    // open the full page from an inline card (floating/fullscreen)

// —— Fullscreen / restore / close (desktop; mobile is already fullscreen) ——
window.tt.expand();  window.tt.collapse();  window.tt.close();
const dm = await window.tt.getDisplayMode();          // {maximized, mobile} — whether fullscreen / whether mobile
window.tt.onEvent('displayChanged', (p) => updateFullscreenChip(p.maximized)); // two-way sync with the host capsule's "fullscreen/restore"
window.tt.onEvent('viewportChanged', (p) => relayout(p.width, p.height));       // iframe size change → responsive re-layout

// —— Branding: tint the host capsule header/background ——
window.tt.setHeaderColor('#4f46e5');
window.tt.setBackgroundColor('#fdf6e3');
Host buttons · haptics · Telegram-style (no authorization needed)

A mini-app controls the host chrome's buttons and receives their click events (two-way) — the bottom main button mainButton, the header back button backButton, haptics hapticFeedback. This lets a mini-app integrate deeply with the host UI (rather than being an isolated page).

// MainButton (the host's big bottom button, controlled by the mini-app + receives clicks) — Telegram-style
window.tt.mainButton.setText('Submit order').show();  // chainable; setText/setParams/show/hide/enable/disable/showProgress/hideProgress
window.tt.mainButton.onClick(() => {                  // click callback (host → mini-app event); offClick to unbind
  window.tt.mainButton.showProgress();
  submit().finally(() => window.tt.mainButton.hideProgress());
});
// BackButton (the host header's back button)
window.tt.backButton.show();                           // show/hide/onClick/offClick
window.tt.backButton.onClick(() => history.back());
// Generic event listening (same as the onClick above)
window.tt.onEvent('mainButtonClicked', handler);
window.tt.onEvent('backButtonClicked', handler);
window.tt.offEvent('mainButtonClicked', handler);      // unbind
// HapticFeedback
window.tt.hapticFeedback.impactOccurred('light');      // light|medium|heavy|rigid|soft
window.tt.hapticFeedback.notificationOccurred('success'); // error|success|warning
window.tt.hapticFeedback.selectionChanged();
Theme · cloud storage · Telegram-style

colorScheme / themeParams keep the mini-app's colors consistent with the host and switch with light/dark; locale syncs with the host's i18n.

// —— Theme (consistent with the host's colors, switches with light/dark) ——
window.tt.colorScheme;          // 'light' | 'dark'
window.tt.themeParams;          // {bgColor,textColor,hintColor,linkColor,buttonColor,buttonTextColor,secondaryBgColor}
document.body.style.background = window.tt.themeParams.bgColor;   // use the host color, consistent with the host
window.tt.onEvent('themeChanged', () => {                        // fires when the host toggles light/dark (same as onThemeChange)
  applyTheme(window.tt.colorScheme, window.tt.themeParams);
});
// —— Locale i18n (synced with the host; the SDK already sets <html lang>) ——
window.tt.locale;               // e.g. 'zh-CN' / 'en-US'; same as tt.context().locale
window.tt.onLocaleChange((locale) => renderInLang(locale));      // or onEvent('localeChanged')

Reference

Error handling

Every window.tt.* returns a Promise and rejects an Error on failure. Production mini-apps must .catch / try-catch every call. Common err.message:

err.message Meaning / suggested handling
User denied authorization The on-demand authorization prompt was denied → guide a retry
User cancelled The conversation picker/preview was cancelled → stay silent
Call timed out The host was unresponsive for a long time (rare) → prompt a retry
Data too large / too many documents / too many storage items Quota exceeded → trim the data
public reads are limited to pub_-prefixed public collections Collection naming mismatch → use a pub_ prefix
Forbidden (403) A non-developer used scope=all → no permission
Network error / Failed to fetch Network failure → friendly prompt + retry
// Every tt.* returns a Promise and rejects an Error on failure; handle with .catch / try-catch.
window.tt.getProfile()
  .then((me) => { /* … */ })
  .catch((err) => {
    switch (err.message) {
      case 'User denied authorization': /* guide the user to retry authorization */ break;
      case 'User cancelled':            /* the user cancelled the conversation picker, stay silent */ break;
      case 'Call timed out':            /* the host was unresponsive for a long time (rare), prompt a retry */ break;
      default:                          /* quota / permission (403) / network, etc — give a friendly prompt */
    }
  });
Authorization model

On-demand authorization: opening a mini-app doesn't require granting all permissions up front; the host prompts for a single item only when a capability is first called (allow/deny). The user can "trust this mini-app" to grant everything at once, or toggle items individually and view usage records on the settings page. The backend still re-validates on every call (defense in depth). UI/window/device/theme/cross-app capabilities are usable without authorization.

Capability (scope) Description Sensitive
user.profile Get your nickname and avatar
cloud.data Cloud data (collections; orders/records etc.)
storage.kv Data storage (KV)
media.upload Upload images/files (incl. drive tt.drive)
im.share Share a card to chat
im.send Send messages
im.read Read conversation history Sensitive
im.room Multiplayer rooms: send/receive messages and read room chat on your behalf Sensitive
text.lookup Word lookup/translate (the selected text is sent to a translation service) Sensitive
text.provider Lookup provider (this mini-app's page acts as the lookup/translate popover) Sensitive
Visibility
  • Public: appears in "Discover" and search; anyone can find it.
  • Unlisted: not in discover/search; reachable only via a shared card or copied link (deep link) — for private-traffic spread without public exposure. Toggle it in the console with one click.
  • Open mode (desktop): the console's "Open mode" toggles "floating (default) / fullscreen" — canvas/whiteboard/editor apps set fullscreen to fill the screen on open; lightweight cards/forms use floating. You can also declare the initial value in manifest.json's display. Mobile is always fullscreen, unaffected by this setting.
Versions & publishing

Version model: draft → in review → ready → live.

All historical versions are kept, with one-click rollback to any historical version (instant swap of the live version). Rejections show the reason in the notification center.

Constraints & quotas
  • Cloud data: single document ≤ 8KB, ≤ 500 documents per (mini-app, user), list() ≤ 200 at a time (by newest); use listPage() cursor pagination (mine/all) for more. Note: doing frontend aggregation (counting/averaging) directly with list() will under-count the oldest part when a collection exceeds 200 and give a low result — for full totals use listPage pagination or accept an approximation.
  • KV: single value ≤ 8KB, ≤ 64 keys per (mini-app, user).
  • Uploaded images ≤ 4MB; uploaded files ≤ 20MB; message sending is rate-limited (≤ 20 per user per minute); room signal payload ≤ 2KB; tt.link single message ≤ 2KB, throttled 25/s.
  • The code bundle is a single-file HTML (prefer pure DOM rendering; avoid innerHTML to prevent XSS).
  • Tokens are short-lived (about 2 hours); the host silently renews after expiry; capability calls are re-validated by the backend.

Reference examples: the repo's applets/food (ordering, cloud data) and applets/repair (repair requests) are both pure-frontend + cloud-data mini-apps.