diff --git a/.github/workflows/extension.yml b/.github/workflows/extension.yml
new file mode 100644
index 0000000..8fe89b8
--- /dev/null
+++ b/.github/workflows/extension.yml
@@ -0,0 +1,164 @@
+name: Extension Build & Chrome Web Store Publish
+
+on:
+ pull_request:
+ paths:
+ - 'manifest.json'
+ - 'src/**'
+ - 'icons/**'
+ - 'scripts/**'
+ - '.github/workflows/extension.yml'
+ push:
+ branches:
+ - master
+ paths:
+ - 'manifest.json'
+ - 'src/**'
+ - 'icons/**'
+ workflow_dispatch:
+ inputs:
+ publish_type:
+ description: 'DEFAULT_PUBLISH goes live after review; STAGED_PUBLISH waits for a manual publish in the dashboard'
+ type: choice
+ options:
+ - DEFAULT_PUBLISH
+ - STAGED_PUBLISH
+ default: DEFAULT_PUBLISH
+ cancel_pending:
+ description: 'Cancel an older submission that is still in review and replace it'
+ type: boolean
+ default: false
+
+permissions:
+ contents: read
+
+concurrency:
+ group: extension-${{ github.ref }}
+ # Never interrupt a store upload halfway; superseded PR runs can be cancelled
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ build:
+ name: Validate & package
+ runs-on: ubuntu-latest
+ outputs:
+ version: ${{ steps.package.outputs.version }}
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - name: Require a version bump when extension code changes
+ if: github.event_name == 'pull_request'
+ env:
+ BASE_REF: ${{ github.base_ref }}
+ run: |
+ changed=$(git diff --name-only "origin/${BASE_REF}...HEAD" -- manifest.json src icons)
+ if [ -z "$changed" ]; then
+ echo "No shipped files changed; version bump not required."
+ exit 0
+ fi
+ base_version=$(git show "origin/${BASE_REF}:manifest.json" | node -e "process.stdout.write(JSON.parse(require('fs').readFileSync(0,'utf8')).version)")
+ head_version=$(node -p "require('./manifest.json').version")
+ echo "Base v${base_version} -> PR v${head_version}"
+ newer=$(node -e "
+ const [a, b] = process.argv.slice(1).map(v => v.split('.').map(Number));
+ let r = 0;
+ for (let i = 0; i < 4 && r === 0; i++) r = Math.sign((a[i] || 0) - (b[i] || 0));
+ process.stdout.write(String(r > 0));
+ " "$head_version" "$base_version")
+ if [ "$newer" != "true" ]; then
+ echo "::error file=manifest.json::Extension files changed but v${head_version} is not higher than v${base_version} on ${BASE_REF}. Bump \"version\" in manifest.json so the merge ships to the Chrome Web Store."
+ exit 1
+ fi
+
+ - name: Validate and package extension
+ id: package
+ run: |
+ zip_path=$(node scripts/build-extension.mjs --out dist | tail -n 1)
+ echo "zip=${zip_path}" >> "$GITHUB_OUTPUT"
+ echo "version=$(node -p "require('./manifest.json').version")" >> "$GITHUB_OUTPUT"
+
+ - name: Upload package artifact
+ uses: actions/upload-artifact@v4
+ with:
+ name: tabstack-extension
+ path: dist/*.zip
+ if-no-files-found: error
+ retention-days: 30
+
+ publish:
+ name: Publish to Chrome Web Store
+ needs: build
+ if: github.event_name != 'pull_request'
+ runs-on: ubuntu-latest
+ environment:
+ name: chrome-web-store
+ url: https://chromewebstore.google.com/detail/tabstack/${{ vars.CWS_EXTENSION_ID || 'pnjlcnpebjggdmkhbopnibjgechfbfjg' }}
+ permissions:
+ contents: write # create the GitHub release for the shipped version
+ env:
+ CWS_PUBLISHER_ID: ${{ secrets.CWS_PUBLISHER_ID }}
+ CWS_EXTENSION_ID: ${{ vars.CWS_EXTENSION_ID || 'pnjlcnpebjggdmkhbopnibjgechfbfjg' }}
+ CWS_SERVICE_ACCOUNT_JSON: ${{ secrets.CWS_SERVICE_ACCOUNT_JSON }}
+ CWS_CLIENT_ID: ${{ secrets.CWS_CLIENT_ID }}
+ CWS_CLIENT_SECRET: ${{ secrets.CWS_CLIENT_SECRET }}
+ CWS_REFRESH_TOKEN: ${{ secrets.CWS_REFRESH_TOKEN }}
+ CWS_PUBLISH_TYPE: ${{ inputs.publish_type || 'DEFAULT_PUBLISH' }}
+ CWS_CANCEL_PENDING: ${{ inputs.cancel_pending && 'true' || 'false' }}
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+
+ - name: Setup Node.js
+ uses: actions/setup-node@v4
+ with:
+ node-version: 20
+
+ - name: Check store credentials
+ id: creds
+ run: |
+ if [ -z "$CWS_PUBLISHER_ID" ] || { [ -z "$CWS_SERVICE_ACCOUNT_JSON" ] && [ -z "$CWS_REFRESH_TOKEN" ]; }; then
+ echo "::warning::Chrome Web Store secrets are not configured, so nothing was published. See docs/PUBLISHING.md."
+ echo "configured=false" >> "$GITHUB_OUTPUT"
+ else
+ echo "configured=true" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Compare with store version
+ id: check
+ if: steps.creds.outputs.configured == 'true'
+ run: node scripts/cws-publish.mjs check
+
+ - name: Download package artifact
+ if: steps.check.outputs.should_publish == 'true'
+ uses: actions/download-artifact@v4
+ with:
+ name: tabstack-extension
+ path: dist
+
+ - name: Upload and submit for review
+ id: publish
+ if: steps.check.outputs.should_publish == 'true'
+ run: node scripts/cws-publish.mjs publish "dist/tabstack-${{ needs.build.outputs.version }}.zip"
+
+ - name: Create GitHub release
+ if: steps.publish.outputs.submitted_version != ''
+ env:
+ GH_TOKEN: ${{ github.token }}
+ VERSION: ${{ steps.publish.outputs.submitted_version }}
+ run: |
+ if gh release view "v${VERSION}" >/dev/null 2>&1; then
+ echo "Release v${VERSION} already exists"
+ else
+ gh release create "v${VERSION}" "dist/tabstack-${VERSION}.zip" \
+ --target "${GITHUB_SHA}" \
+ --title "TabStack v${VERSION}" \
+ --generate-notes
+ fi
diff --git a/README.md b/README.md
index a767fe6..4477813 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
Smart Tab Auto-Collapse & RAM Saver for Chromium Browsers
- Automatically clusters same-site tabs into native collapsible groups, expands only your active stack (Accordion Mode), and frees system memory.
+ Automatically clusters same-site tabs into native collapsible groups, expands only your active stack (Accordion Mode), frees system memory, and brings back windows you close by mistake.
-### 5. ๐งผ Clean, Minimal & Clutter-Free UI
+### 5. ๐ Session Snapshots (Never Lose a Window Again)
+Closed the wrong window? TabStack keeps a local copy of every open window and saves it the moment the window closes. It also takes periodic snapshots (every 1h, 3h, 6h, 24h or 7 days) and keeps the session that was open before the browser last restarted. Open the **Sessions** tab in the popup and click **Restore** to reopen the tabs in a new window with pinned tabs and tab groups (names, colors, collapsed state) intact. Snapshots can be exported to and imported from JSON in Settings.
+
+
+
+
+
+### 6. ๐งผ Clean, Minimal & Clutter-Free UI
Designed with an intuitive, distraction-free interface that gets completely out of your way. Fast, accessible, lightweight, and works seamlessly out of the box with zero complex setup.
---
@@ -85,6 +92,7 @@ Designed with an intuitive, distraction-free interface that gets completely out
* **Zero Injected Content Scripts:** TabStack never touches or inspects webpage DOM contents.
* **100% Local Execution:** No remote analytics, tracking pixels, or data collection. Your open tabs and browsing history never leave your machine.
+* **Local-Only Snapshots:** Session snapshots (tab URLs, titles and group names) are stored in your browser's extension storage and are never uploaded. Turn them off or delete them anytime in Settings.
* **Lightweight Service Worker:** Event-driven architecture with debounced operations (150ms) to ensure 0% CPU overhead.
---
@@ -106,6 +114,9 @@ Get TabStack directly from the official store:
3. Enable **Developer mode** in the top-right corner.
4. Click **Load unpacked** and select the root `tabstack/` folder.
+### Releasing
+Merging a version bump to `master` publishes it automatically: GitHub Actions validates and packages the extension, uploads it to the Chrome Web Store through the v2 API, and submits it for review. PRs that change extension code must bump `"version"` in `manifest.json`. One-time credential setup is in **[docs/PUBLISHING.md](docs/PUBLISHING.md)**.
+
### Running the Landing Page Locally
```bash
cd landing
diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md
new file mode 100644
index 0000000..1946111
--- /dev/null
+++ b/docs/PUBLISHING.md
@@ -0,0 +1,94 @@
+# Publishing to the Chrome Web Store
+
+Merges to `master` that touch the extension (`manifest.json`, `src/`, `icons/`) are uploaded to the Chrome Web Store and submitted for review automatically by [`.github/workflows/extension.yml`](../.github/workflows/extension.yml). It uses the [Chrome Web Store API v2](https://developer.chrome.com/docs/webstore/using-api). The v1 API stops working on October 15, 2026.
+
+## How a release flows
+
+1. **Open a PR** that changes the extension and bumps `"version"` in `manifest.json`. The PR check fails if extension files changed but the version isn't higher than `master`'s.
+2. **CI validates and packages** the extension: manifest sanity checks, a syntax check of every script, and a zip of `manifest.json`, `src/` and `icons/` attached to the run as an artifact.
+3. **Merge.** The publish job compares the manifest version with the store:
+ - newer than the published and pending versions: uploads the zip and submits it for review
+ - already published or already in review: skips, with the reason in the job summary
+4. **Google reviews the update.** It goes live automatically when approved (usually within a few days).
+5. A **GitHub Release** `vX.Y.Z` is created with the submitted zip attached.
+
+Merges that only touch the landing page, docs or README never publish. The landing page has its own workflow (`deploy.yml`).
+
+## One-time setup
+
+You need your **Publisher ID** from the [Developer Dashboard](https://chrome.google.com/webstore/devconsole) under **Account โ Publisher settings**. The publishing Google account must have 2-step verification turned on.
+
+Then pick **one** of the two auth methods below.
+
+### Option A: Service account (recommended)
+
+Service account keys don't expire, and they aren't tied to your personal Google login.
+
+1. In the [Google Cloud Console](https://console.cloud.google.com), create or pick a project and **enable the "Chrome Web Store API"**.
+2. Go to **IAM & Admin โ Service accounts** and create a service account. It doesn't need any IAM roles.
+3. Open the service account, go to **Keys โ Add key โ Create new key โ JSON**, and download the file.
+4. In the Chrome Web Store [Developer Dashboard](https://chrome.google.com/webstore/devconsole), go to **Account**, find the service account section, and add the service account's email address. Only one service account can be added per publisher.
+5. Add the secrets to the `chrome-web-store` environment (the commands are under [Add the GitHub secrets](#add-the-github-secrets)):
+ - `CWS_PUBLISHER_ID`
+ - `CWS_SERVICE_ACCOUNT_JSON`: the full contents of the JSON key file
+
+If your Google Cloud organization blocks service account key creation, use Option B.
+
+### Option B: OAuth client + refresh token
+
+1. In the Cloud Console, **enable the "Chrome Web Store API"**.
+2. Configure the **OAuth consent screen** (External), then **publish the app to "In production"**. While the app is in "Testing", refresh tokens expire after 7 days and the pipeline starts failing.
+3. Create an **OAuth client ID** of type *Web application* with the authorized redirect URI `https://developers.google.com/oauthplayground`.
+4. Open the [OAuth Playground](https://developers.google.com/oauthplayground). Click the gear icon, tick **Use your own OAuth credentials**, and enter your client ID and secret. Authorize the scope `https://www.googleapis.com/auth/chromewebstore` with the publisher account, then click **Exchange authorization code for tokens** and copy the **refresh token**.
+5. Add the secrets to the `chrome-web-store` environment:
+ - `CWS_PUBLISHER_ID`
+ - `CWS_CLIENT_ID`
+ - `CWS_CLIENT_SECRET`
+ - `CWS_REFRESH_TOKEN`
+
+### Add the GitHub secrets
+
+You can add them in **Settings โ Environments โ New environment โ `chrome-web-store`**, or with the GitHub CLI:
+
+```bash
+gh secret set CWS_PUBLISHER_ID --env chrome-web-store --repo YarooqH/tabstack
+```
+
+```bash
+gh secret set CWS_SERVICE_ACCOUNT_JSON --env chrome-web-store --repo YarooqH/tabstack < path/to/service-account-key.json
+```
+
+Optional:
+- **Required reviewers** on the `chrome-web-store` environment, to approve each store submission by hand before it runs.
+- A repository **variable** `CWS_EXTENSION_ID` if the store item ID ever changes. It defaults to `pnjlcnpebjggdmkhbopnibjgechfbfjg`.
+
+Until the secrets exist, the publish job skips with a warning instead of failing.
+
+## Running it manually
+
+**Actions โ Extension Build & Chrome Web Store Publish โ Run workflow** on `master` offers two options:
+
+- **publish_type**: `STAGED_PUBLISH` holds the update after review approval until you click Publish in the dashboard. `DEFAULT_PUBLISH` (the default) goes live as soon as it's approved.
+- **cancel_pending**: cancels an older version that is still in review and submits the current one instead. Without it, the job stops and tells you a submission is already pending.
+
+## Local commands
+
+```bash
+node scripts/build-extension.mjs
+```
+
+This validates the extension and writes `dist/tabstack-.zip`. It needs the `zip` CLI.
+
+```bash
+CWS_PUBLISHER_ID=... CWS_EXTENSION_ID=pnjlcnpebjggdmkhbopnibjgechfbfjg CWS_SERVICE_ACCOUNT_JSON="$(cat key.json)" node scripts/cws-publish.mjs check
+```
+
+This compares `manifest.json` with what's in the store and changes nothing.
+
+## What the pipeline does not update
+
+The API only uploads packages. Do these in the Developer Dashboard when they change:
+
+- Store listing text, screenshots and promo images
+- **Privacy practices**: permission justifications and data-usage disclosures. For example, a newly added permission such as `unlimitedStorage` needs a justification before review.
+- Distribution and visibility settings
diff --git a/docs/images/tabstack-session-snapshots.png b/docs/images/tabstack-session-snapshots.png
new file mode 100644
index 0000000..16c9956
Binary files /dev/null and b/docs/images/tabstack-session-snapshots.png differ
diff --git a/landing/app.js b/landing/app.js
index 5f0b0cc..170ddf2 100644
--- a/landing/app.js
+++ b/landing/app.js
@@ -455,11 +455,9 @@ function setupCompareSlider() {
function setupStickyStorytelling() {
const stepBlocks = document.querySelectorAll('.story-step-block');
- const visualPanes = {
- 1: document.getElementById('visualPane-1'),
- 2: document.getElementById('visualPane-2'),
- 3: document.getElementById('visualPane-3')
- };
+ const visualPanes = Object.fromEntries(
+ [...document.querySelectorAll('.story-visual-pane')].map(pane => [pane.id.replace('visualPane-', ''), pane])
+ );
if (!stepBlocks.length) return;
diff --git a/landing/index.html b/landing/index.html
index db7e92a..4ef6cfe 100644
--- a/landing/index.html
+++ b/landing/index.html
@@ -5,9 +5,9 @@
TabStack โ Make your tab bar usable again
-
+
-
+
@@ -95,7 +95,7 @@
A clean tab bar in one click.
- Native domain grouping, auto-collapsing stacks, and zero script injection. Free up memory and keep your browser fast.
+ Native domain grouping, auto-collapsing stacks, and zero script injection. Free up memory, and get back any window you close by mistake.
@@ -982,6 +982,13 @@
RAM Saver puts tabs to sleep
Background tabs automatically hibernate to free up memory, restoring instantly the moment you click back.
+
+
+ 04
+
Closed the wrong window? Get it back
+
TabStack saves every window the moment it closes and takes periodic snapshots. One click reopens all the tabs with their stacks, colors, and pins intact.
Last updated: August 17, 2026 ยท TabStack Extension
+
Last updated: October 8, 2026 ยท TabStack Extension
@@ -155,7 +155,7 @@
Privacy Policy
1. Overview and Single Purpose
-
TabStack is an open-source browser extension designed for Chromium-based browsers (Chrome, Brave, Arc, Edge). Its single purpose is to organize and cluster open tabs by domain into native collapsible tab groups and hibernate dormant background tabs to reclaim memory.
+
TabStack is an open-source browser extension designed for Chromium-based browsers (Chrome, Brave, Arc, Edge). Its single purpose is to organize and cluster open tabs by domain into native collapsible tab groups and hibernate dormant background tabs to reclaim memory. To protect that organization, it can also keep a local snapshot of your open windows so they can be reopened after being closed by mistake.
@@ -163,7 +163,8 @@
2. Data Collection and Usage
TabStack adheres to a strict zero-telemetry policy:
No Personal Information: We do not ask for or collect names, email addresses, usernames, IP addresses, or device identifiers.
-
No Web History Collection: Although TabStack inspects open tab URLs in local memory to group tabs by domain name (e.g. github.com), this data is processed ephemerally in active memory and is never logged, stored as history, or sent to external servers.
+
No Web History Collection: TabStack inspects open tab URLs to group tabs by domain name (e.g. github.com). It does not read your browsing history and never sends tab data to any server.
+
Local Session Snapshots: When Session Snapshots are enabled (the default), TabStack saves the URL, title, pinned state and tab group of the tabs in your open windows to your browser's local extension storage, so you can restore a window after closing it. Snapshots stay on your device, are trimmed automatically to the limits you choose, and can be turned off, exported or deleted at any time in Settings.
No Telemetry or Analytics: TabStack contains zero analytics libraries, zero tracking pixels, and zero background network requests. It operates completely offline.
No Remote Code: TabStack does not load or execute external scripts, remote CDNs, or dynamic code. All extension logic is fully contained within the installed package.
@@ -191,11 +192,15 @@
3. Chromium Permissions Justification
storage
-
Allows persisting your local extension preferences (such as accordion mode toggles, hibernation timers, and custom group colors) inside your browser's local storage.
+
Allows persisting your local extension preferences (such as accordion mode toggles, hibernation timers, and custom group colors) and your session snapshots inside your browser's local storage.
+
+
+
unlimitedStorage
+
Lets session snapshots of large windows be stored locally without hitting the default extension storage cap. Nothing is stored outside your device.
alarms
-
Allows scheduling lightweight periodic background timers to evaluate idle tab inactivity and trigger hibernation.
+
Allows scheduling lightweight periodic background timers to evaluate idle tab inactivity, trigger hibernation, and take periodic session snapshots.
@@ -203,7 +208,7 @@
3. Chromium Permissions Justification
4. Data Storage and Retention
-
All user configurations and preferences are stored exclusively on your local machine using Chromium's chrome.storage.local API. If you uninstall TabStack or clear your browser extension data, all local preferences are permanently removed.
+
All user configurations, preferences and session snapshots are stored exclusively on your local machine using Chromium's chrome.storage.local API. Session snapshots are kept only up to the retention limits set in Settings and can be deleted at any time. If you uninstall TabStack or clear your browser extension data, all local preferences and snapshots are permanently removed.
diff --git a/landing/style.css b/landing/style.css
index 6841d9f..2448633 100644
--- a/landing/style.css
+++ b/landing/style.css
@@ -683,7 +683,7 @@ body {
.showcase-tabs {
display: grid;
- grid-template-columns: repeat(4, 1fr);
+ grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 8px;
margin-bottom: 14px;
}
@@ -4598,11 +4598,23 @@ body {
.steps-pipeline-grid {
display: grid;
- grid-template-columns: repeat(3, 1fr);
+ grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 16px;
list-style: none;
}
+@media (max-width: 960px) {
+ .steps-pipeline-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+@media (max-width: 560px) {
+ .steps-pipeline-grid {
+ grid-template-columns: 1fr;
+ }
+}
+
.pipeline-step-card {
display: flex;
flex-direction: column;
@@ -4656,6 +4668,8 @@ body {
/* Step 1 Visual: Floating Chips */
.step-mini-icon-mesh {
display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
gap: 6px;
}
@@ -4683,6 +4697,8 @@ body {
/* Step 2 Visual: Cluster flow */
.step-cluster-animation {
display: flex;
+ flex-wrap: wrap;
+ justify-content: center;
gap: 6px;
}
@@ -4762,6 +4778,46 @@ body {
font-family: var(--font-mono);
}
+/* Step 4 Visual: Restore Flow */
+.step-restore-wrap {
+ width: 100%;
+}
+
+.restore-flow-card {
+ background: var(--bg-surface);
+ border: 1px solid var(--border-subtle);
+ border-radius: 6px;
+ padding: 6px 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.restore-flow-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ font-size: 10px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.restore-flow-chip {
+ font-size: 9px;
+ font-weight: 600;
+ color: var(--btn-primary-text);
+ background: var(--btn-primary-bg);
+ padding: 1px 6px;
+ border-radius: 3px;
+}
+
+.restore-flow-status {
+ font-size: 9px;
+ color: var(--accent-green);
+ font-family: var(--font-mono);
+}
+
.step-card-text-wrap {
display: flex;
flex-direction: column;
@@ -5770,6 +5826,107 @@ body {
.row-dot.orange { background: #f59e0b; }
.row-dot.green { background: #10b981; }
.row-dot.red-orange { background: #ff4500; }
+.row-dot.purple { background: #a855f7; }
+.row-dot.blue { background: #3b82f6; }
+
+/* Story Step 4: Session Snapshots */
+.mock-restore-card {
+ background: var(--bg-surface);
+ border: 1px solid var(--border-subtle);
+ border-radius: 8px;
+ padding: 14px 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.mock-restore-card .collapse-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+}
+
+.restore-snapshot-list {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.restore-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ background: var(--bg-input);
+ border: 1px solid transparent;
+ padding: 7px 10px;
+ border-radius: 6px;
+}
+
+.restore-row.is-target {
+ border-color: var(--border-medium);
+}
+
+.restore-row-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ min-width: 0;
+}
+
+.restore-row-meta strong {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-primary);
+}
+
+.restore-row-meta span {
+ font-family: var(--font-mono);
+ font-size: 10px;
+ color: var(--text-tertiary);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.restore-btn-mock {
+ flex-shrink: 0;
+ font-size: 11px;
+ font-weight: 600;
+ color: var(--text-secondary);
+ background: var(--bg-surface);
+ border: 1px solid var(--border-subtle);
+ padding: 4px 10px;
+ border-radius: 5px;
+}
+
+.restore-row.is-target .restore-btn-mock {
+ color: var(--btn-primary-text);
+ background: var(--btn-primary-bg);
+ border-color: var(--btn-primary-bg);
+}
+
+.restore-done-line {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-family: var(--font-mono);
+ font-size: 11px;
+ color: var(--accent-green);
+}
+
+.story-visual-pane.active .anim-restore-press {
+ animation: restorePress 0.35s ease 0.55s both;
+}
+
+.story-visual-pane.active .anim-restore-done {
+ animation: slideRowIn 0.35s cubic-bezier(0.16, 1, 0.3, 1) 0.85s backwards;
+}
+
+@keyframes restorePress {
+ 0%, 100% { transform: scale(1); }
+ 45% { transform: scale(0.92); }
+}
/* Step 2: Accordion Focus Animations */
.story-visual-pane.active .anim-accordion-unfold {
@@ -6313,3 +6470,58 @@ body {
color: var(--text-primary);
}
+
+/* ==========================================================================
+ Small Screens: Header Fit & Install Cards
+ ========================================================================== */
+
+/* Grid items default to min-width: auto, so the clone command forced the cards wider than the screen */
+.install-methods > * {
+ min-width: 0;
+}
+
+.code-box {
+ gap: 10px;
+}
+
+.code-box code {
+ min-width: 0;
+ overflow-x: auto;
+ white-space: nowrap;
+ scrollbar-width: none;
+}
+
+@media (max-width: 480px) {
+ .header-container {
+ padding: 0 16px;
+ }
+
+ .nav-actions {
+ gap: 6px;
+ }
+
+ /* The hero "Source Code" button and the footer still link to GitHub */
+ .nav-actions .btn-icon {
+ display: none;
+ }
+
+ .nav-actions .btn-primary {
+ padding: 6px 12px;
+ }
+
+ .install-card {
+ padding: 24px 18px;
+ }
+}
+
+@media (max-width: 359px) {
+ .brand-title {
+ display: none;
+ }
+
+ /* Keep the demo's tab strip row inside the screen: status dot + memory only */
+ .sim-telemetry-badge .tag-text,
+ .sim-telemetry-badge .tag-divider {
+ display: none;
+ }
+}
diff --git a/manifest.json b/manifest.json
index 3da9a2d..e1dc567 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,13 +2,14 @@
"manifest_version": 3,
"name": "TabStack",
"short_name": "TabStack",
- "version": "1.1.0",
+ "version": "1.3.0",
"description": "Automatically clusters same-site tabs into native collapsible groups, expands only active stacks, and saves memory.",
"permissions": [
"tabs",
"tabGroups",
"storage",
- "alarms"
+ "alarms",
+ "unlimitedStorage"
],
"background": {
"service_worker": "src/background/service-worker.js",
diff --git a/scripts/build-extension.mjs b/scripts/build-extension.mjs
new file mode 100644
index 0000000..e374b6f
--- /dev/null
+++ b/scripts/build-extension.mjs
@@ -0,0 +1,73 @@
+#!/usr/bin/env node
+/**
+ * Validates the extension source and packages it into a Chrome Web Store zip.
+ * Usage: node scripts/build-extension.mjs [--out dist]
+ * Prints the zip path on the last line of stdout. Requires the `zip` CLI.
+ */
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const outIndex = process.argv.indexOf('--out');
+const outDir = path.resolve(root, outIndex > -1 ? process.argv[outIndex + 1] : 'dist');
+
+// Only these paths ship in the store package
+const PACKAGE_PATHS = ['manifest.json', 'src', 'icons'];
+
+function fail(message) {
+ console.error(`::error::${message}`);
+ process.exit(1);
+}
+
+function walk(dir) {
+ return fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => {
+ const full = path.join(dir, entry.name);
+ return entry.isDirectory() ? walk(full) : [full];
+ });
+}
+
+const manifest = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8'));
+
+if (manifest.manifest_version !== 3) fail('manifest_version must be 3');
+if (!/^\d+(\.\d+){0,3}$/.test(manifest.version || '')) fail(`Invalid manifest version "${manifest.version}"`);
+
+// Every file the manifest points at must exist
+const referenced = [
+ manifest.background?.service_worker,
+ manifest.action?.default_popup,
+ manifest.options_ui?.page,
+ ...Object.values(manifest.icons || {}),
+ ...Object.values(manifest.action?.default_icon || {})
+].filter(Boolean);
+for (const file of referenced) {
+ if (!fs.existsSync(path.join(root, file))) fail(`manifest.json references missing file: ${file}`);
+}
+
+// Syntax-check every script that ships. They are all ES modules, but `node --check`
+// treats .js as CommonJS on some Node versions, so check .mjs copies instead.
+const checkDir = fs.mkdtempSync(path.join(os.tmpdir(), 'tabstack-check-'));
+try {
+ for (const file of walk(path.join(root, 'src')).filter(f => f.endsWith('.js'))) {
+ const copy = path.join(checkDir, `${path.relative(root, file).replace(/[\\/]/g, '__')}.mjs`);
+ fs.copyFileSync(file, copy);
+ try {
+ execFileSync(process.execPath, ['--check', copy], { stdio: 'pipe' });
+ } catch (err) {
+ fail(`Syntax error in ${path.relative(root, file)}\n${err.stderr}`);
+ }
+ }
+} finally {
+ fs.rmSync(checkDir, { recursive: true, force: true });
+}
+
+fs.mkdirSync(outDir, { recursive: true });
+const zipPath = path.join(outDir, `tabstack-${manifest.version}.zip`);
+fs.rmSync(zipPath, { force: true });
+execFileSync('zip', ['-r', '-X', '-q', zipPath, ...PACKAGE_PATHS, '-x', '*.DS_Store', '-x', 'icons/*.svg'], { cwd: root, stdio: 'inherit' });
+
+console.log(`Validated manifest v${manifest.version} and packaged ${PACKAGE_PATHS.join(', ')}`);
+console.log(zipPath);
diff --git a/scripts/cws-publish.mjs b/scripts/cws-publish.mjs
new file mode 100644
index 0000000..0d81dca
--- /dev/null
+++ b/scripts/cws-publish.mjs
@@ -0,0 +1,237 @@
+#!/usr/bin/env node
+/**
+ * Chrome Web Store publisher (API v2, no dependencies).
+ *
+ * node scripts/cws-publish.mjs check Compares manifest.json with the store version
+ * node scripts/cws-publish.mjs publish Uploads the zip and submits it for review
+ *
+ * Environment:
+ * CWS_PUBLISHER_ID, CWS_EXTENSION_ID Required
+ * CWS_SERVICE_ACCOUNT_JSON Service account key (preferred), or
+ * CWS_CLIENT_ID, CWS_CLIENT_SECRET, CWS_REFRESH_TOKEN OAuth client + refresh token
+ * CWS_PUBLISH_TYPE DEFAULT_PUBLISH (default) or STAGED_PUBLISH
+ * CWS_CANCEL_PENDING "true" to cancel an older submission still in review
+ */
+
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { fileURLToPath } from 'node:url';
+
+const API = 'https://chromewebstore.googleapis.com';
+const SCOPE = 'https://www.googleapis.com/auth/chromewebstore';
+const TOKEN_URL = 'https://oauth2.googleapis.com/token';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const env = process.env;
+
+class PublishError extends Error {}
+
+// Throws instead of process.exit() so open fetch sockets close before Node exits
+function fail(message) {
+ throw new PublishError(message);
+}
+
+function setOutput(name, value) {
+ if (env.GITHUB_OUTPUT) fs.appendFileSync(env.GITHUB_OUTPUT, `${name}=${value}\n`);
+}
+
+function summary(markdown) {
+ console.log(markdown);
+ if (env.GITHUB_STEP_SUMMARY) fs.appendFileSync(env.GITHUB_STEP_SUMMARY, `${markdown}\n`);
+}
+
+/** Compares dotted Chrome versions (1-4 integer parts). Returns -1, 0 or 1. */
+function compareVersions(a, b) {
+ const pa = String(a).split('.').map(Number);
+ const pb = String(b).split('.').map(Number);
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const diff = (pa[i] || 0) - (pb[i] || 0);
+ if (diff !== 0) return diff > 0 ? 1 : -1;
+ }
+ return 0;
+}
+
+const base64url = (input) => Buffer.from(input).toString('base64url');
+
+async function getAccessToken() {
+ let body;
+
+ if (env.CWS_SERVICE_ACCOUNT_JSON) {
+ let key;
+ try {
+ key = JSON.parse(env.CWS_SERVICE_ACCOUNT_JSON);
+ } catch {
+ fail('CWS_SERVICE_ACCOUNT_JSON is not valid JSON');
+ }
+ const now = Math.floor(Date.now() / 1000);
+ const unsigned = `${base64url(JSON.stringify({ alg: 'RS256', typ: 'JWT' }))}.${base64url(JSON.stringify({
+ iss: key.client_email,
+ scope: SCOPE,
+ aud: TOKEN_URL,
+ iat: now,
+ exp: now + 3600
+ }))}`;
+ const signature = crypto.createSign('RSA-SHA256').update(unsigned).sign(key.private_key, 'base64url');
+ body = new URLSearchParams({
+ grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
+ assertion: `${unsigned}.${signature}`
+ });
+ } else if (env.CWS_CLIENT_ID && env.CWS_CLIENT_SECRET && env.CWS_REFRESH_TOKEN) {
+ body = new URLSearchParams({
+ grant_type: 'refresh_token',
+ client_id: env.CWS_CLIENT_ID,
+ client_secret: env.CWS_CLIENT_SECRET,
+ refresh_token: env.CWS_REFRESH_TOKEN
+ });
+ } else {
+ fail('No credentials: set CWS_SERVICE_ACCOUNT_JSON, or CWS_CLIENT_ID + CWS_CLIENT_SECRET + CWS_REFRESH_TOKEN');
+ }
+
+ const res = await fetch(TOKEN_URL, { method: 'POST', body });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok || !json.access_token) {
+ fail(`Could not get an access token (${res.status}): ${json.error_description || json.error || 'unknown error'}`);
+ }
+ return json.access_token;
+}
+
+async function api(token, method, url, { body, contentType } = {}) {
+ const res = await fetch(url, {
+ method,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ ...(contentType ? { 'Content-Type': contentType } : {})
+ },
+ body
+ });
+ const text = await res.text();
+ let json;
+ try {
+ json = text ? JSON.parse(text) : {};
+ } catch {
+ json = { raw: text };
+ }
+ if (!res.ok) {
+ const detail = json.error?.message || json.raw || text;
+ fail(`${method} ${url.replace(API, '')} failed (${res.status}): ${detail}`);
+ }
+ return json;
+}
+
+function itemPath() {
+ if (!env.CWS_PUBLISHER_ID || !env.CWS_EXTENSION_ID) fail('CWS_PUBLISHER_ID and CWS_EXTENSION_ID are required');
+ return `publishers/${env.CWS_PUBLISHER_ID}/items/${env.CWS_EXTENSION_ID}`;
+}
+
+function revisionVersion(revision) {
+ return revision?.distributionChannels?.[0]?.crxVersion || null;
+}
+
+async function fetchStatus(token) {
+ return api(token, 'GET', `${API}/v2/${itemPath()}:fetchStatus`);
+}
+
+/**
+ * Decides whether the local manifest version should be submitted
+ */
+function evaluate(status, localVersion) {
+ const published = revisionVersion(status.publishedItemRevisionStatus);
+ const submitted = revisionVersion(status.submittedItemRevisionStatus);
+ const submittedState = status.submittedItemRevisionStatus?.state || null;
+
+ if (status.takenDown) return { publish: false, reason: 'The item is taken down in the store; resolve it in the Developer Dashboard.', published, submitted, submittedState, error: true };
+ if (published && compareVersions(localVersion, published) <= 0) {
+ return { publish: false, reason: `v${localVersion} is not newer than the published v${published}. Bump "version" in manifest.json to ship.`, published, submitted, submittedState };
+ }
+ if (submitted && compareVersions(localVersion, submitted) <= 0 && ['PENDING_REVIEW', 'STAGED'].includes(submittedState)) {
+ return { publish: false, reason: `v${submitted} is already submitted (${submittedState}).`, published, submitted, submittedState };
+ }
+ return { publish: true, reason: `v${localVersion} is newer than the store (published: ${published || 'none'}).`, published, submitted, submittedState };
+}
+
+async function check() {
+ const localVersion = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8')).version;
+ const token = await getAccessToken();
+ const status = await fetchStatus(token);
+ const result = evaluate(status, localVersion);
+
+ setOutput('should_publish', String(result.publish));
+ setOutput('version', localVersion);
+ summary(`### Chrome Web Store check\n\n| | Version | State |\n|---|---|---|\n| manifest.json | ${localVersion} | |\n| Published | ${result.published || 'โ'} | ${status.publishedItemRevisionStatus?.state || 'โ'} |\n| Submitted | ${result.submitted || 'โ'} | ${result.submittedState || 'โ'} |\n\n${result.publish ? '๐' : 'โญ๏ธ'} ${result.reason}`);
+ if (status.warned) console.log('::warning::The store item has an active policy warning. Check the Developer Dashboard.');
+ if (result.error) fail(result.reason);
+}
+
+async function waitForUpload(token) {
+ for (let attempt = 0; attempt < 30; attempt++) {
+ await new Promise(r => setTimeout(r, 5000));
+ const status = await fetchStatus(token);
+ const state = status.lastAsyncUploadState;
+ console.log(`Upload state: ${state}`);
+ if (state === 'SUCCEEDED') return;
+ if (state === 'FAILED' || state === 'NOT_FOUND') fail(`Upload processing ended with ${state}. Check the Developer Dashboard for details.`);
+ }
+ fail('Timed out waiting for the upload to finish processing');
+}
+
+async function publish(zipFile) {
+ if (!zipFile || !fs.existsSync(zipFile)) fail(`Package not found: ${zipFile}`);
+ const localVersion = JSON.parse(fs.readFileSync(path.join(root, 'manifest.json'), 'utf8')).version;
+ const token = await getAccessToken();
+
+ // Re-check right before uploading in case another run already shipped this version
+ const status = await fetchStatus(token);
+ const decision = evaluate(status, localVersion);
+ if (!decision.publish) {
+ summary(`โญ๏ธ Skipped publish: ${decision.reason}`);
+ if (decision.error) fail(decision.reason);
+ return;
+ }
+
+ if (decision.submittedState === 'PENDING_REVIEW') {
+ if (env.CWS_CANCEL_PENDING !== 'true') {
+ fail(`v${decision.submitted} is still in review. Wait for it, or re-run with CWS_CANCEL_PENDING=true to replace it with v${localVersion}.`);
+ }
+ console.log(`Cancelling pending submission v${decision.submitted}`);
+ await api(token, 'POST', `${API}/v2/${itemPath()}:cancelSubmission`);
+ }
+
+ console.log(`Uploading ${path.basename(zipFile)} (${fs.statSync(zipFile).size} bytes)`);
+ const upload = await api(token, 'POST', `${API}/upload/v2/${itemPath()}:upload`, {
+ body: fs.readFileSync(zipFile),
+ contentType: 'application/zip'
+ });
+ console.log(`Upload response: ${JSON.stringify(upload)}`);
+
+ if (upload.uploadState === 'IN_PROGRESS' || upload.uploadState === 'UPLOAD_IN_PROGRESS') {
+ await waitForUpload(token);
+ } else if (upload.uploadState !== 'SUCCEEDED') {
+ fail(`Upload failed with state ${upload.uploadState}: ${JSON.stringify(upload)}`);
+ }
+
+ const publishType = env.CWS_PUBLISH_TYPE || 'DEFAULT_PUBLISH';
+ const result = await api(token, 'POST', `${API}/v2/${itemPath()}:publish`, {
+ body: JSON.stringify({ publishType }),
+ contentType: 'application/json'
+ });
+
+ setOutput('submitted_version', localVersion);
+ setOutput('state', result.state || '');
+ const warnings = (result.warningInfo?.warnings || []).map(w => `- ${w.reason}: ${w.description}`).join('\n');
+ summary(`### Submitted v${localVersion} to the Chrome Web Store\n\nState: \`${result.state}\` (${publishType}). Google reviews the update before it reaches users.${warnings ? `\n\nWarnings:\n${warnings}` : ''}`);
+}
+
+const [command, arg] = process.argv.slice(2);
+try {
+ if (command === 'check') {
+ await check();
+ } else if (command === 'publish') {
+ await publish(arg);
+ } else {
+ fail('Usage: cws-publish.mjs check | publish ');
+ }
+} catch (err) {
+ console.error(`::error::${err instanceof PublishError ? err.message : err.stack}`);
+ process.exitCode = 1;
+}
diff --git a/src/background/service-worker.js b/src/background/service-worker.js
index afcb762..cc406e7 100644
--- a/src/background/service-worker.js
+++ b/src/background/service-worker.js
@@ -3,7 +3,7 @@
* Ultra-lightweight, event-driven, zero persistent memory overhead
*/
-import { DEFAULT_SETTINGS, MESSAGE_TYPES } from '../shared/constants.js';
+import { DEFAULT_SETTINGS, MESSAGE_TYPES, SNAPSHOT_KINDS } from '../shared/constants.js';
import { getSettings, setSetting, addStash } from '../shared/storage.js';
import { debounce } from './utils.js';
import {
@@ -22,14 +22,31 @@ import {
discardEligibleTabs,
discardSingleTab
} from './discarder.js';
+import {
+ SNAPSHOT_ALARM,
+ isWindowRestoring,
+ refreshLiveState,
+ scheduleLiveStateRefresh,
+ markWindowClosing,
+ handleWindowClosed,
+ takeSnapshot,
+ getSnapshots,
+ deleteSnapshot,
+ clearSnapshots,
+ importSnapshots,
+ restoreSnapshot,
+ syncSnapshotAlarm
+} from './snapshots.js';
// Debounced tab group coordinator (150ms) to prevent CPU churn
const debouncedGroupTabs = debounce((windowId) => {
- if (typeof windowId === 'number') {
+ if (typeof windowId === 'number' && !isWindowRestoring(windowId)) {
groupTabsInWindow(windowId);
}
}, 150);
+const SNAPSHOT_SETTING_KEYS = ['snapshotsEnabled', 'snapshotIntervalMinutes'];
+
// Setup on install / update
chrome.runtime.onInstalled.addListener(async (details) => {
console.log('[TabStack] Installed / Updated:', details.reason);
@@ -53,6 +70,9 @@ chrome.runtime.onInstalled.addListener(async (details) => {
delayInMinutes: 2
});
+ await syncSnapshotAlarm();
+ refreshLiveState();
+
// Perform initial group on last focused window
try {
const win = await chrome.windows.getLastFocused({ populate: false });
@@ -64,9 +84,15 @@ chrome.runtime.onInstalled.addListener(async (details) => {
}
});
+chrome.runtime.onStartup.addListener(async () => {
+ await syncSnapshotAlarm();
+ refreshLiveState();
+});
+
// Event Listeners for Tab Life-cycle
chrome.tabs.onCreated.addListener((tab) => {
if (tab.windowId) debouncedGroupTabs(tab.windowId);
+ scheduleLiveStateRefresh();
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
@@ -74,11 +100,31 @@ chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' || changeInfo.url) {
if (tab.windowId) debouncedGroupTabs(tab.windowId);
}
+ if (changeInfo.url || changeInfo.title || changeInfo.pinned !== undefined || changeInfo.groupId !== undefined) {
+ scheduleLiveStateRefresh();
+ }
});
chrome.tabs.onRemoved.addListener((tabId, removeInfo) => {
- if (!removeInfo.isWindowClosing && removeInfo.windowId) {
+ if (removeInfo.isWindowClosing) {
+ markWindowClosing(removeInfo.windowId);
+ } else if (removeInfo.windowId) {
debouncedGroupTabs(removeInfo.windowId);
+ scheduleLiveStateRefresh();
+ }
+});
+
+chrome.tabs.onMoved.addListener(() => scheduleLiveStateRefresh());
+chrome.tabs.onAttached.addListener(() => scheduleLiveStateRefresh());
+chrome.tabGroups.onUpdated.addListener(() => scheduleLiveStateRefresh());
+
+chrome.windows.onRemoved.addListener((windowId) => {
+ handleWindowClosed(windowId);
+});
+
+chrome.storage.onChanged.addListener((changes, areaName) => {
+ if (areaName === 'local' && SNAPSHOT_SETTING_KEYS.some(key => key in changes)) {
+ syncSnapshotAlarm();
}
});
@@ -91,6 +137,8 @@ chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'tabstack-ram-saver') {
runTabDiscarder();
+ } else if (alarm.name === SNAPSHOT_ALARM) {
+ takeSnapshot(SNAPSHOT_KINDS.AUTO);
}
});
@@ -239,6 +287,35 @@ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
return { success: true };
}
+ case MESSAGE_TYPES.GET_SNAPSHOTS: {
+ return { success: true, snapshots: await getSnapshots() };
+ }
+
+ case MESSAGE_TYPES.TAKE_SNAPSHOT: {
+ const snapshot = await takeSnapshot(SNAPSHOT_KINDS.MANUAL);
+ return { success: !!snapshot, snapshot };
+ }
+
+ case MESSAGE_TYPES.RESTORE_SNAPSHOT: {
+ const { snapshotId, windowIndex } = message;
+ return await restoreSnapshot(snapshotId, Number.isInteger(windowIndex) ? windowIndex : null);
+ }
+
+ case MESSAGE_TYPES.DELETE_SNAPSHOT: {
+ await deleteSnapshot(message.snapshotId);
+ return { success: true };
+ }
+
+ case MESSAGE_TYPES.CLEAR_SNAPSHOTS: {
+ await clearSnapshots();
+ return { success: true };
+ }
+
+ case MESSAGE_TYPES.IMPORT_SNAPSHOTS: {
+ const count = await importSnapshots(message.snapshots);
+ return { success: true, count };
+ }
+
default:
return { success: false, error: 'Unknown message type' };
}
diff --git a/src/background/snapshots.js b/src/background/snapshots.js
new file mode 100644
index 0000000..06b80fe
--- /dev/null
+++ b/src/background/snapshots.js
@@ -0,0 +1,459 @@
+/**
+ * TabStack Session Snapshots
+ * Keeps a persisted mirror of every open window so closed windows, crashes and
+ * timed snapshots can be restored later into a fresh window with groups intact.
+ */
+
+import { getSettings } from '../shared/storage.js';
+import { CHROMIUM_COLORS, SNAPSHOT_KINDS } from '../shared/constants.js';
+
+// CHROMIUM_COLORS drives domain color hashing, so orange is added here instead
+const GROUP_COLORS = new Set([...CHROMIUM_COLORS, 'orange']);
+
+export const SNAPSHOT_ALARM = 'tabstack-session-snapshot';
+
+// Stored outside DEFAULT_SETTINGS so "Reset to Defaults" never wipes them
+const LIVE_STATE_KEY = 'sessionLiveState';
+const SNAPSHOTS_KEY = 'sessionSnapshots';
+const LAST_AUTO_KEY = 'sessionLastAutoSnapshotAt';
+const BOOT_MARKER_KEY = 'sessionBootMarker';
+
+// Auto-grouping stays paused this long after a restore so late page loads don't regroup it
+const RESTORE_GRACE_MS = 3000;
+
+const MAX_CLOSED_WINDOWS = 25;
+const MAX_PREVIOUS_SESSIONS = 5;
+const MAX_MANUAL_SNAPSHOTS = 50;
+const MIN_TABS_FOR_CLOSED_WINDOW = 2;
+const LIVE_STATE_REFRESH_MS = 1000;
+// A mirrored window missing from the browser this long without a close event is dropped
+const GHOST_WINDOW_MS = 60 * 1000;
+
+const IGNORED_URL_PREFIXES = [
+ 'chrome://newtab', 'brave://newtab', 'edge://newtab', 'opera://startpage',
+ 'chrome-search://', 'about:blank', 'chrome://new-tab-page'
+];
+
+// Windows currently being rebuilt by restoreSnapshot; auto-grouping skips them
+const restoringWindowIds = new Set();
+
+// Windows whose tabs are being torn down; their mirrored copy must not be overwritten
+const closingWindowIds = new Set();
+
+// All storage read-modify-writes go through this chain so they never interleave
+let queue = Promise.resolve();
+function enqueue(task) {
+ const run = queue.then(task, task);
+ queue = run.catch((err) => console.error('[TabStack Snapshots]', err));
+ return run;
+}
+
+export function isWindowRestoring(windowId) {
+ return restoringWindowIds.has(windowId);
+}
+
+export function markWindowClosing(windowId) {
+ closingWindowIds.add(windowId);
+}
+
+function isRestorableUrl(url) {
+ if (!url || /^(javascript|data):/i.test(url)) return false;
+ return !IGNORED_URL_PREFIXES.some(prefix => url.startsWith(prefix));
+}
+
+function serializeWindow(win, groups) {
+ const tabs = (win.tabs || [])
+ .map(t => ({
+ url: t.url || t.pendingUrl || '',
+ title: t.title || '',
+ pinned: !!t.pinned,
+ groupId: t.groupId ?? -1,
+ favIconUrl: t.favIconUrl && /^https?:/.test(t.favIconUrl) && t.favIconUrl.length < 400 ? t.favIconUrl : ''
+ }))
+ .filter(t => isRestorableUrl(t.url));
+
+ const usedGroupIds = new Set(tabs.map(t => t.groupId));
+ return {
+ windowId: win.id,
+ tabs,
+ groups: groups
+ .filter(g => g.windowId === win.id && usedGroupIds.has(g.id))
+ .map(g => ({ id: g.id, title: g.title || '', color: g.color || 'grey', collapsed: !!g.collapsed }))
+ };
+}
+
+async function captureOpenWindows() {
+ const [windows, groups] = await Promise.all([
+ chrome.windows.getAll({ populate: true, windowTypes: ['normal'] }),
+ chrome.tabGroups.query({})
+ ]);
+ return windows
+ .filter(w => !w.incognito)
+ .map(w => serializeWindow(w, groups));
+}
+
+function countTabs(windows) {
+ return windows.reduce((sum, w) => sum + w.tabs.length, 0);
+}
+
+function signatureOf(windows) {
+ return JSON.stringify(windows.map(w => w.tabs.map(t => t.url)));
+}
+
+async function readSnapshots() {
+ const items = await chrome.storage.local.get({ [SNAPSHOTS_KEY]: [] });
+ return Array.isArray(items[SNAPSHOTS_KEY]) ? items[SNAPSHOTS_KEY] : [];
+}
+
+/**
+ * Inserts a snapshot newest-first and trims each kind to its retention cap
+ */
+async function insertSnapshot(kind, windows) {
+ if (windows.length === 0) return null;
+
+ const settings = await getSettings();
+ const snapshots = await readSnapshots();
+
+ // Skip automatic snapshots that are identical to the newest one of the same kind
+ if (kind === SNAPSHOT_KINDS.AUTO || kind === SNAPSHOT_KINDS.PREVIOUS_SESSION) {
+ const latest = snapshots.find(s => s.kind === kind);
+ if (latest && signatureOf(latest.windows) === signatureOf(windows)) return null;
+ }
+
+ const snapshot = {
+ id: `snap_${Date.now()}_${Math.random().toString(36).slice(2, 7)}`,
+ kind,
+ createdAt: new Date().toISOString(),
+ tabCount: countTabs(windows),
+ windows: windows.map(({ tabs, groups }) => ({ tabs, groups }))
+ };
+
+ const caps = {
+ [SNAPSHOT_KINDS.AUTO]: settings.snapshotKeepCount || 24,
+ [SNAPSHOT_KINDS.CLOSED_WINDOW]: MAX_CLOSED_WINDOWS,
+ [SNAPSHOT_KINDS.PREVIOUS_SESSION]: MAX_PREVIOUS_SESSIONS,
+ [SNAPSHOT_KINDS.MANUAL]: MAX_MANUAL_SNAPSHOTS
+ };
+ const seen = {};
+ const trimmed = [snapshot, ...snapshots].filter(s => {
+ seen[s.kind] = (seen[s.kind] || 0) + 1;
+ return seen[s.kind] <= (caps[s.kind] ?? MAX_MANUAL_SNAPSHOTS);
+ });
+
+ await chrome.storage.local.set({ [SNAPSHOTS_KEY]: trimmed });
+ return snapshot;
+}
+
+/**
+ * On the first event of a new browser session, archive whatever the mirror held
+ * when the previous session ended (crash, power loss, or a restore that failed).
+ * chrome.storage.session survives service worker restarts but not browser restarts.
+ */
+async function archivePreviousSessionIfNeeded() {
+ const marker = await chrome.storage.session.get(BOOT_MARKER_KEY);
+ if (marker[BOOT_MARKER_KEY]) return;
+
+ const items = await chrome.storage.local.get({ [LIVE_STATE_KEY]: {} });
+ const previous = Object.values(items[LIVE_STATE_KEY] || {}).filter(w => w.tabs?.length > 0);
+ if (previous.length > 0) {
+ await insertSnapshot(SNAPSHOT_KINDS.PREVIOUS_SESSION, previous);
+ }
+
+ // Window ids are reused across browser sessions, so the old mirror must go
+ await chrome.storage.local.set({ [LIVE_STATE_KEY]: {} });
+ await chrome.storage.session.set({ [BOOT_MARKER_KEY]: Date.now() });
+}
+
+/**
+ * Refreshes the persisted mirror of open windows. Windows are only removed from
+ * the mirror by handleWindowClosed, so a refresh racing a window close can't
+ * erase the copy we need to archive.
+ */
+export function refreshLiveState() {
+ return enqueue(async () => {
+ await archivePreviousSessionIfNeeded();
+
+ const windows = await captureOpenWindows();
+ const items = await chrome.storage.local.get({ [LIVE_STATE_KEY]: {} });
+ const liveState = items[LIVE_STATE_KEY] || {};
+ const now = Date.now();
+
+ for (const win of windows) {
+ if (closingWindowIds.has(win.windowId)) continue;
+ liveState[win.windowId] = { ...win, updatedAt: now };
+ }
+
+ const openIds = new Set(windows.map(w => String(w.windowId)));
+ for (const [id, entry] of Object.entries(liveState)) {
+ if (openIds.has(id)) continue;
+ if (!entry.missingSince) {
+ entry.missingSince = now;
+ } else if (now - entry.missingSince > GHOST_WINDOW_MS) {
+ delete liveState[id];
+ }
+ }
+
+ await chrome.storage.local.set({ [LIVE_STATE_KEY]: liveState });
+ });
+}
+
+let refreshTimer = null;
+
+/**
+ * Coalesces bursts of tab events into one refresh at most every second.
+ * Unlike a debounce, a page that keeps changing its title can't postpone it forever.
+ */
+export function scheduleLiveStateRefresh() {
+ if (refreshTimer) return;
+ refreshTimer = setTimeout(() => {
+ refreshTimer = null;
+ refreshLiveState();
+ }, LIVE_STATE_REFRESH_MS);
+}
+
+/**
+ * Archives a window's last known tabs when it closes
+ * @param {number} windowId
+ */
+export function handleWindowClosed(windowId) {
+ return enqueue(async () => {
+ closingWindowIds.delete(windowId);
+ await archivePreviousSessionIfNeeded();
+
+ const items = await chrome.storage.local.get({ [LIVE_STATE_KEY]: {} });
+ const liveState = items[LIVE_STATE_KEY] || {};
+ const closed = liveState[windowId];
+ if (!closed?.tabs) return;
+
+ delete liveState[windowId];
+ await chrome.storage.local.set({ [LIVE_STATE_KEY]: liveState });
+
+ const settings = await getSettings();
+ if (settings.snapshotClosedWindows && closed.tabs.length >= MIN_TABS_FOR_CLOSED_WINDOW) {
+ await insertSnapshot(SNAPSHOT_KINDS.CLOSED_WINDOW, [closed]);
+ }
+ });
+}
+
+/**
+ * Saves every open window as one snapshot
+ * @param {'auto'|'manual'} kind
+ */
+export function takeSnapshot(kind = SNAPSHOT_KINDS.MANUAL) {
+ return enqueue(async () => {
+ await archivePreviousSessionIfNeeded();
+ const windows = (await captureOpenWindows()).filter(w => w.tabs.length > 0);
+ if (kind === SNAPSHOT_KINDS.AUTO) {
+ await chrome.storage.local.set({ [LAST_AUTO_KEY]: Date.now() });
+ }
+ return insertSnapshot(kind, windows);
+ });
+}
+
+export async function getSnapshots() {
+ await queue;
+ return readSnapshots();
+}
+
+export function deleteSnapshot(snapshotId) {
+ return enqueue(async () => {
+ const snapshots = await readSnapshots();
+ await chrome.storage.local.set({ [SNAPSHOTS_KEY]: snapshots.filter(s => s.id !== snapshotId) });
+ });
+}
+
+export function clearSnapshots() {
+ return enqueue(() => chrome.storage.local.set({ [SNAPSHOTS_KEY]: [] }));
+}
+
+/**
+ * Merges snapshots from an exported JSON file, skipping ids already present
+ * @param {Array} incoming
+ * @returns {Promise} Count of imported snapshots
+ */
+export function importSnapshots(incoming) {
+ return enqueue(async () => {
+ const snapshots = await readSnapshots();
+ const existingIds = new Set(snapshots.map(s => s.id));
+ const valid = (Array.isArray(incoming) ? incoming : [])
+ .filter(s => s && s.id && !existingIds.has(s.id) && Array.isArray(s.windows))
+ .map(s => ({
+ id: String(s.id),
+ kind: Object.values(SNAPSHOT_KINDS).includes(s.kind) ? s.kind : SNAPSHOT_KINDS.MANUAL,
+ createdAt: s.createdAt || new Date().toISOString(),
+ windows: s.windows
+ .map(w => ({
+ tabs: (Array.isArray(w.tabs) ? w.tabs : [])
+ .filter(t => t && typeof t.url === 'string' && isRestorableUrl(t.url))
+ .map(t => ({
+ url: t.url,
+ title: String(t.title || ''),
+ pinned: !!t.pinned,
+ groupId: Number.isInteger(t.groupId) ? t.groupId : -1,
+ favIconUrl: typeof t.favIconUrl === 'string' && /^https?:/.test(t.favIconUrl) ? t.favIconUrl : ''
+ })),
+ groups: (Array.isArray(w.groups) ? w.groups : [])
+ .filter(g => g && Number.isInteger(g.id))
+ .map(g => ({
+ id: g.id,
+ title: String(g.title || ''),
+ color: GROUP_COLORS.has(g.color) ? g.color : 'grey',
+ collapsed: !!g.collapsed
+ }))
+ }))
+ .filter(w => w.tabs.length > 0)
+ }))
+ .filter(s => s.windows.length > 0)
+ .map(s => ({ ...s, tabCount: countTabs(s.windows) }));
+
+ const merged = [...snapshots, ...valid]
+ .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
+ await chrome.storage.local.set({ [SNAPSHOTS_KEY]: merged });
+ return valid.length;
+ });
+}
+
+/**
+ * (Re)creates the periodic snapshot alarm from current settings
+ */
+export async function syncSnapshotAlarm() {
+ const settings = await getSettings();
+ const existing = await chrome.alarms.get(SNAPSHOT_ALARM);
+ const period = Number(settings.snapshotIntervalMinutes) || 360;
+
+ if (!settings.snapshotsEnabled) {
+ if (existing) await chrome.alarms.clear(SNAPSHOT_ALARM);
+ return;
+ }
+
+ if (!existing || existing.periodInMinutes !== period) {
+ // Chrome may drop alarms on browser restart, so count from the last auto snapshot
+ // rather than from now; otherwise frequent restarts could postpone it forever
+ const items = await chrome.storage.local.get({ [LAST_AUTO_KEY]: 0 });
+ const elapsedMinutes = (Date.now() - items[LAST_AUTO_KEY]) / 60000;
+ const delayInMinutes = Math.max(1, Math.min(period, period - elapsedMinutes));
+ await chrome.alarms.create(SNAPSHOT_ALARM, { periodInMinutes: period, delayInMinutes });
+ }
+}
+
+/**
+ * Waits until a freshly created tab has committed its URL so it can be discarded
+ * without losing the page it should come back to
+ */
+function waitForCommit(tabId, timeoutMs = 15000) {
+ const isCommitted = (tab) => tab.status === 'complete' || (tab.url && tab.title && tab.title !== tab.url);
+
+ return new Promise((resolve) => {
+ const done = () => {
+ clearTimeout(timer);
+ chrome.tabs.onUpdated.removeListener(listener);
+ resolve();
+ };
+ const listener = (id, changeInfo, tab) => {
+ if (id === tabId && isCommitted(tab)) done();
+ };
+ const timer = setTimeout(done, timeoutMs);
+ chrome.tabs.onUpdated.addListener(listener);
+
+ // Fast pages may have finished before the listener was attached
+ chrome.tabs.get(tabId).then(tab => { if (isCommitted(tab)) done(); }, done);
+ });
+}
+
+/**
+ * Opens a stored window in a new browser window, recreating pins and tab groups
+ * @param {{ tabs: Array, groups: Array }} storedWindow
+ * @param {boolean} sleepBackgroundTabs
+ * @returns {Promise<{ opened: number, skipped: number }>}
+ */
+async function restoreWindow(storedWindow, sleepBackgroundTabs) {
+ const tabs = storedWindow.tabs.filter(t => isRestorableUrl(t.url));
+ if (tabs.length === 0) return { opened: 0, skipped: 0 };
+
+ const win = await chrome.windows.create({ focused: true });
+ restoringWindowIds.add(win.id);
+ const placeholderTabIds = (win.tabs || []).map(t => t.id);
+
+ const createdByOldGroup = new Map();
+ const backgroundTabIds = [];
+ let opened = 0;
+ let skipped = 0;
+
+ try {
+ for (const stored of tabs) {
+ try {
+ const tab = await chrome.tabs.create({
+ windowId: win.id,
+ url: stored.url,
+ pinned: stored.pinned,
+ active: opened === 0
+ });
+ opened++;
+ if (opened > 1) backgroundTabIds.push(tab.id);
+
+ if (!stored.pinned && stored.groupId !== -1) {
+ if (!createdByOldGroup.has(stored.groupId)) createdByOldGroup.set(stored.groupId, []);
+ createdByOldGroup.get(stored.groupId).push(tab.id);
+ }
+ } catch {
+ // file:// or other URLs the extension isn't allowed to open
+ skipped++;
+ }
+ }
+
+ if (opened > 0 && placeholderTabIds.length > 0) {
+ await chrome.tabs.remove(placeholderTabIds).catch(() => {});
+ }
+
+ for (const group of storedWindow.groups || []) {
+ const tabIds = createdByOldGroup.get(group.id);
+ if (!tabIds || tabIds.length === 0) continue;
+ try {
+ const groupId = await chrome.tabs.group({ tabIds, createProperties: { windowId: win.id } });
+ await chrome.tabGroups.update(groupId, {
+ title: group.title,
+ color: group.color,
+ collapsed: group.collapsed
+ });
+ } catch (err) {
+ console.warn('[TabStack Snapshots] Could not recreate group:', err);
+ }
+ }
+ } finally {
+ setTimeout(() => restoringWindowIds.delete(win.id), RESTORE_GRACE_MS);
+ }
+
+ if (sleepBackgroundTabs) {
+ // Not awaited: discarding waits on page commits and shouldn't hold up the reply
+ Promise.all(backgroundTabIds.map(async (tabId) => {
+ await waitForCommit(tabId);
+ await chrome.tabs.discard(tabId).catch(() => {});
+ }));
+ }
+
+ return { opened, skipped };
+}
+
+/**
+ * Restores a snapshot (or one window of it) into new browser windows
+ * @param {string} snapshotId
+ * @param {number|null} windowIndex Restore only this window when set
+ */
+export async function restoreSnapshot(snapshotId, windowIndex = null) {
+ const snapshots = await getSnapshots();
+ const snapshot = snapshots.find(s => s.id === snapshotId);
+ if (!snapshot) return { success: false, error: 'Snapshot not found' };
+
+ const settings = await getSettings();
+ const targets = windowIndex === null ? snapshot.windows : [snapshot.windows[windowIndex]].filter(Boolean);
+
+ let opened = 0;
+ let skipped = 0;
+ for (const storedWindow of targets) {
+ const result = await restoreWindow(storedWindow, !!settings.autoDiscardEnabled);
+ opened += result.opened;
+ skipped += result.skipped;
+ }
+
+ return { success: opened > 0, opened, skipped };
+}
diff --git a/src/options/options.css b/src/options/options.css
index 274b969..e1fec11 100644
--- a/src/options/options.css
+++ b/src/options/options.css
@@ -413,3 +413,14 @@ kbd {
font-weight: 500;
color: var(--accent-green);
}
+
+.btn:disabled,
+.select-input:disabled {
+ opacity: 0.5;
+ cursor: default;
+}
+
+.setting-row.setting-row-wrap {
+ flex-wrap: wrap;
+ gap: 12px;
+}
diff --git a/src/options/options.html b/src/options/options.html
index d3e2948..8a5b72f 100644
--- a/src/options/options.html
+++ b/src/options/options.html
@@ -37,6 +37,7 @@
TabStack
+
+
+
Session Snapshots
+
Keep a local copy of your open windows so a closed window or a lost session can be reopened with its tabs, pins and groups.
+
+
+
+
+
+ Keeps the tabs of any window with 2 or more tabs the moment it closes, including right before the browser quits.
+
+
+
+
+
+
+
+ Saves every open window on a schedule. Unchanged sessions are skipped.
+
+
+
+
+
+
+
+ How often a periodic snapshot is taken while the browser is open.
+
+
+
+
+
+
+
+ Older periodic snapshots are deleted. Closed windows keep the latest 25.
+