Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion docs/unique-pattern-proposal.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
# Proposal: Add `unique_pattern` Field to Rule Schema

## Status
🟡 **Proposed** - Not yet implemented
⚪ **Superseded** - Not implemented. Solved without a new field (#507): when `url_matcher` has
capture groups and `url_fragment` has no `$n` placeholders, the captured values are the unique key,
so tabs are duplicates only if they capture the same values. See `_getUniqueKey` in
`src/common/helpers.ts`.

## Problem Statement

Expand Down
25 changes: 9 additions & 16 deletions src/background/TabRulesService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
_setStorage,
_shouldSkipUrl,
} from '../common/storage';
import { _processUrlFragment } from '../common/helpers';
import { _getUniqueKey } from '../common/helpers';

/**
* Service responsible for applying tab modification rules
Expand Down Expand Up @@ -70,21 +70,15 @@ export class TabRulesService {
}
}

const processedUrlFragment = _processUrlFragment(
urlFragment,
currentTab.url,
rule?.tab?.url_matcher
);
const uniqueKey = _getUniqueKey(urlFragment, currentTab.url, rule?.tab?.url_matcher);

// Without url_matcher every tab of the rule is one group; with it, the group is the processed fragment
const lockKey = rule?.tab?.url_matcher
? `${rule?.id ?? ''}|${processedUrlFragment}`
: `${rule?.id ?? ''}`;
// Without url_matcher every tab of the rule is one group; with it, the group is the unique key
const lockKey = rule?.tab?.url_matcher ? `${rule?.id ?? ''}|${uniqueKey}` : `${rule?.id ?? ''}`;

const previous = this.uniqueLocks.get(lockKey) ?? Promise.resolve();
const run = previous
.catch(() => undefined)
.then(() => this.closeDuplicates(rule, urlFragment, processedUrlFragment, currentTab));
.then(() => this.closeDuplicates(rule, urlFragment, uniqueKey, currentTab));
this.uniqueLocks.set(lockKey, run);

try {
Expand All @@ -97,7 +91,7 @@ export class TabRulesService {
private async closeDuplicates(
rule: Rule,
urlFragment: string,
processedUrlFragment: string,
uniqueKey: string,
currentTab: chrome.tabs.Tab
): Promise<void> {
const tabs = await this.queryTabs({});
Expand Down Expand Up @@ -151,11 +145,10 @@ export class TabRulesService {
continue;
}

// Process the fragment for each tab to compare
const tabProcessedFragment = _processUrlFragment(urlFragment, tab.url, rule.tab.url_matcher);
// Same unique key (captured values or processed fragment) means duplicate
const tabUniqueKey = _getUniqueKey(urlFragment, tab.url, rule.tab.url_matcher);

// Compare processed fragments instead of raw URL
if (tabProcessedFragment === processedUrlFragment && tab.id !== currentTab.id) {
if (tabUniqueKey === uniqueKey && tab.id !== currentTab.id) {
// Remove beforeunload handler from the duplicate tab before closing it
try {
await chrome.scripting.executeScript({
Expand Down
2 changes: 1 addition & 1 deletion src/background/__tests__/TabRulesService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ vi.mock('../../common/storage', () => ({

// Mock helpers module
vi.mock('../../common/helpers', () => ({
_processUrlFragment: vi.fn((_fragment, url) => url),
_getUniqueKey: vi.fn((_fragment, url) => url),
}));

import {
Expand Down
54 changes: 54 additions & 0 deletions src/background/__tests__/TabRulesService.unique.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -437,4 +437,58 @@ describe('TabRulesService - GitHub Unique Issue Test', () => {
expect(mockChrome.tabs.remove).not.toHaveBeenCalled();
});
});

describe('url_matcher capture groups as unique key (#507)', () => {
// The sample GitHub Issues rule: REGEX detection without $ placeholders
const message = {
url_fragment: 'github\\.com/.+/issues/\\d+',
rule: {
id: 'github-issues',
detection: 'REGEX',
url_fragment: 'github\\.com/.+/issues/\\d+',
tab: {
unique: true,
url_matcher: 'github\\.com/.+/issues/(\\d+)',
},
} as Rule,
};

it('should close another tab of the same issue', async () => {
const currentTab = {
id: 1,
url: 'https://github.com/owner/repo/issues/123',
} as chrome.tabs.Tab;
const sameIssue = {
id: 2,
url: 'https://github.com/owner/repo/issues/123#issuecomment-1',
} as chrome.tabs.Tab;
const otherIssue = {
id: 3,
url: 'https://github.com/owner/repo/issues/456',
} as chrome.tabs.Tab;

mockChrome.tabs.query.mockImplementation((_queryInfo: any, callback: any) => {
callback([currentTab, sameIssue, otherIssue]);
});

await service.handleSetUnique(message, currentTab);

expect(mockChrome.tabs.remove).toHaveBeenCalledTimes(1);
expect(mockChrome.tabs.remove).toHaveBeenCalledWith(2);
});

it('should keep tabs of different issues open', async () => {
const tab123 = { id: 1, url: 'https://github.com/owner/repo/issues/123' } as chrome.tabs.Tab;
const tab456 = { id: 2, url: 'https://github.com/owner/repo/issues/456' } as chrome.tabs.Tab;
const tab789 = { id: 3, url: 'https://github.com/other/repo/issues/789' } as chrome.tabs.Tab;

mockChrome.tabs.query.mockImplementation((_queryInfo: any, callback: any) => {
callback([tab123, tab456, tab789]);
});

await service.handleSetUnique(message, tab123);

expect(mockChrome.tabs.remove).not.toHaveBeenCalled();
});
});
});
35 changes: 33 additions & 2 deletions src/common/__tests__/detection-vs-uniqueness.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { _processUrlFragment } from '../helpers';
import { describe, it, expect, vi } from 'vitest';
import { _getUniqueKey, _processUrlFragment } from '../helpers';

/**
* This test demonstrates the fundamental conflict between detection and uniqueness
Expand Down Expand Up @@ -212,4 +212,35 @@ describe('Detection vs Uniqueness Conflict', () => {
// So issue #123 and #456 can coexist!
});
});

describe('_getUniqueKey (#507)', () => {
const matcher = 'github\\.com/.+/issues/(\\d+)';

it('uses the captured values when url_matcher has capture groups', () => {
const fragment = 'github\\.com/.+/issues/\\d+';

expect(_getUniqueKey(fragment, 'https://github.com/a/b/issues/123', matcher)).toBe('["123"]');
expect(_getUniqueKey(fragment, 'https://github.com/a/b/issues/456', matcher)).toBe('["456"]');
});

it('keeps the processed fragment when url_fragment has $ placeholders', () => {
expect(
_getUniqueKey('github.com/issues/$1', 'https://github.com/a/b/issues/123', matcher)
).toBe('github.com/issues/123');
});

it('falls back to url_fragment without url_matcher, without capture groups, or without a match', () => {
const url = 'https://github.com/a/b/issues/123';

expect(_getUniqueKey('github.com', url, null)).toBe('github.com');
expect(_getUniqueKey('github.com', url, 'github\\.com/.+/issues/\\d+')).toBe('github.com');
expect(_getUniqueKey('github.com', 'https://example.com', matcher)).toBe('github.com');
});

it('falls back to url_fragment on an invalid regex', () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined);

expect(_getUniqueKey('github.com', 'https://github.com', '(')).toBe('github.com');
});
});
});
28 changes: 28 additions & 0 deletions src/common/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -334,3 +334,31 @@ export function _processUrlFragment(

return processedFragment;
}

/**
* Computes the key used by the "unique" option to decide whether two tabs are duplicates.
* - url_fragment with $n placeholders: the processed fragment (explicit template)
* - url_matcher with capture groups: the captured values, so e.g. each GitHub issue number
* is its own unique group
* - otherwise: the url_fragment itself, so every tab of the rule is one group
*/
export function _getUniqueKey(
urlFragment: string,
currentUrl: string,
urlMatcher?: string | null
): string {
if (!urlMatcher || urlFragment.includes('$')) {
return _processUrlFragment(urlFragment, currentUrl, urlMatcher);
}

try {
const match = new RegExp(urlMatcher).exec(currentUrl);
if (match && match.length > 1) {
return JSON.stringify(match.slice(1));
}
} catch (e) {
console.error('Tabee: Error computing unique key:', e);
}

return urlFragment;
}
3 changes: 2 additions & 1 deletion src/components/options/center/sections/TabRules/RuleForm.vue
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,8 @@
<div class="label">
<span class="text-xs opacity-80 label-text-alt">
Regex to capture text from URL. Use $0, $1, $2... in Tab Title to reference captured
groups.</span
groups. With "Unique", tabs are duplicates only if they capture the same values
(e.g. the same issue number).</span
>
</div>
<RegexVisualizer class="mt-2" tag="$" :regex="currentRule.tab.url_matcher" />
Expand Down
Loading