diff --git a/e2e/lan-pairing.spec.mjs b/e2e/lan-pairing.spec.mjs index 6dcf9469..555fff95 100644 --- a/e2e/lan-pairing.spec.mjs +++ b/e2e/lan-pairing.spec.mjs @@ -101,3 +101,24 @@ test('a key named before names were capped still adds, in both directions', asyn await stop(ana, ben) } }) + +test('adding back ends it: neither side is asked to add the other again', async () => { + const ana = await startPeer('Ana') + const ben = await startPeer('Ben') + try { + await addPeer(ben, ana) + const settings = await openSettingsPage(ana.page, 'Network') + const benRow = settings.locator('.person', { hasText: ben.name }) + await benRow.getByRole('button', { name: 'Add' }).click() + const shown = ben.page.getByRole('dialog', { name: `${ana.name} wants to add you` }) + const code = (await shown.getByTestId('lan-code').innerText()).replace(/\W/g, '').slice(0, 6) + const adding = ana.page.getByRole('dialog', { name: `Add ${ben.name}` }) + await adding.getByTestId('lan-code-input').fill(code) + await adding.getByRole('button', { name: 'Add', exact: true }).click() + await expect(benRow.getByText('Trusted')).toBeVisible() + await expect(ben.page.getByText(`${ana.name} added you back`)).toBeVisible() + await expect(ben.page.getByRole('dialog', { name: `${ana.name} added you` })).toHaveCount(0) + } finally { + await stop(ana, ben) + } +}) diff --git a/e2e/lan-send.spec.mjs b/e2e/lan-send.spec.mjs index 12ecf301..3328c4cb 100644 --- a/e2e/lan-send.spec.mjs +++ b/e2e/lan-send.spec.mjs @@ -24,6 +24,12 @@ test('a snippet sent on the network opens in a tab under the received band', asy const band = ben.page.getByRole('region', { name: `From ${ana.name}` }) await expect(band).toBeVisible() await expect(band.getByRole('button', { name: 'Save snippet' })).toBeVisible() + await band.getByRole('button', { name: 'Save snippet' }).click() + const lanTag = ben.page.locator('.snippets-section').getByText('lan', { exact: true }) + await expect(lanTag).toBeVisible() + await expect( + ben.page.locator('.snippets-section').getByText(ana.name.toLowerCase(), { exact: true }) + ).toBeVisible() } finally { await stop(ana, ben) } diff --git a/e2e/lanPeers.mjs b/e2e/lanPeers.mjs index 3fe15e9a..956d1e0c 100644 --- a/e2e/lanPeers.mjs +++ b/e2e/lanPeers.mjs @@ -33,8 +33,12 @@ export async function addPeer(adder, holder) { await adding.getByTestId('lan-code-input').fill(code) await adding.getByRole('button', { name: 'Add', exact: true }).click() await expect(row.getByText('Trusted')).toBeVisible() - const back = holder.page.getByRole('dialog', { name: `${adder.name} added you` }) - await back.locator('.dialog-actions').getByRole('button', { name: 'Not now' }).click() + const asked = holder.page.getByRole('dialog', { name: `${adder.name} added you` }) + const addedBack = holder.page.getByText(`${adder.name} added you back`) + await expect(asked.or(addedBack)).toBeVisible() + if (await asked.isVisible()) { + await asked.locator('.dialog-actions').getByRole('button', { name: 'Not now' }).click() + } await closeSettings(adder.page) } diff --git a/src/main/lan/pairing.js b/src/main/lan/pairing.js index 62f0e6fc..136f1b45 100644 --- a/src/main/lan/pairing.js +++ b/src/main/lan/pairing.js @@ -175,10 +175,14 @@ function onReveal(ctx, { header }, conn) { ctx.emit(view(s)) } -function onResult(ctx, { header }, conn) { +// Asking someone you already added to add you back is what made adding each other loop. +async function onResult(ctx, { header }, conn) { const s = ctx.byConn.get(conn) if (!s || s.role !== 'holder') return conn.destroy() - finish(ctx, s, RESULT_STAGE[header.result]) + // The adder closes right after sending this; the close must not win the trust lookup. + s.resulting = true + const isBack = header.result === 'matched' && (await ctx.isTrusted?.(s.peerFp)) + finish(ctx, s, isBack ? 'added-back' : RESULT_STAGE[header.result]) } export function createPairing(deps) { @@ -198,7 +202,7 @@ export function createPairing(deps) { onResult: (frame, conn) => onResult(ctx, frame, conn), onClosed: (conn) => { const s = ctx.byConn.get(conn) - if (s) finish(ctx, s, 'connection-lost') + if (s && !s.resulting) finish(ctx, s, 'connection-lost') }, cancelAll: () => [...ctx.sessions.values()].forEach((s) => finish(ctx, s, 'connection-lost')) } diff --git a/src/main/lan/pairingIpc.js b/src/main/lan/pairingIpc.js index c227c37d..0794eee6 100644 --- a/src/main/lan/pairingIpc.js +++ b/src/main/lan/pairingIpc.js @@ -6,6 +6,7 @@ import { connectTo } from './server' import { pairingKeyText, parsePairingKey } from '../keyText' import { checkedTrustedName, storeTrusted } from '../trustedKeys' import { appendLog } from '../logger' +import { readTrusted } from '../trustedKeys' const FP = /^[0-9a-f]{32}$/ let pairing = null @@ -35,6 +36,7 @@ export function setUpPairing({ lan, identity, onTrustChanged }) { return endpoint ? connectTo(endpoint, handlers) : Promise.reject(new Error('gone')) }, parseKey: parsePairingKey, + isTrusted: async (fp) => (await readTrusted()).some((t) => t.fingerprint === fp), storeKey: async (key, fp, name) => { await storeTrusted(key, fp, await labelFor(fp, name)) onTrustChanged() diff --git a/src/renderer/src/composables/useSaveDiffTarget.js b/src/renderer/src/composables/useSaveDiffTarget.js index a98ff25f..51588545 100644 --- a/src/renderer/src/composables/useSaveDiffTarget.js +++ b/src/renderer/src/composables/useSaveDiffTarget.js @@ -53,7 +53,7 @@ export function useSaveDiffTarget() { name: tabs.active?.customTitle || derivedName(), secure: !tabs.active?.sample, ttl: DEFAULT_TTL_HOURS, - tags: tabs.active?.sample ? [EXAMPLE_TAG] : [] + tags: [...(tabs.active?.suggestedTags ?? []), ...(tabs.active?.sample ? [EXAMPLE_TAG] : [])] } } diff --git a/src/renderer/src/features/lan/itemActions.js b/src/renderer/src/features/lan/itemActions.js index 03ab8cf7..b78bb216 100644 --- a/src/renderer/src/features/lan/itemActions.js +++ b/src/renderer/src/features/lan/itemActions.js @@ -1,19 +1,26 @@ import { blankSnapshot } from '../../utils/tabs' +import { cleanTag } from '../../utils/snippetState' import { useTabsStore } from '../../stores/tabsStore' -const snippetDraft = ({ name, snippet }) => ({ +// `lan/`: the sender nests under lan, and a slash in their name must not nest deeper. +export const receivedTag = (from) => cleanTag(`lan/${String(from ?? '').replace(/\//g, '-')}`) + +const snippetDraft = ({ name, snippet }, tags) => ({ id: null, initialName: name, initialContent: snippet.content, initialLanguage: snippet.language ?? 'auto', - initialTags: snippet.tags ?? [] + initialTags: [...(snippet.tags ?? []), ...tags] }) -export function openReceivedEntry(entry) { +export function openReceivedEntry(entry, from) { const tabs = useTabsStore() - return entry.kind === 'snippet' - ? tabs.openSnippet(snippetDraft(entry), entry.name) - : tabs.open({ ...blankSnapshot(), ...entry.snapshot }, { name: entry.name }) + const tags = from ? [receivedTag(from)] : [] + if (entry.kind === 'snippet') return tabs.openSnippet(snippetDraft(entry, tags), entry.name) + const id = tabs.open({ ...blankSnapshot(), ...entry.snapshot }, { name: entry.name }) + const tab = tabs.tabs.find((t) => t.id === id) + if (tab) tab.suggestedTags = tags + return id } export const arePopupsShown = ({ popups, silencedUntil }, now = Date.now()) => diff --git a/src/renderer/src/features/lan/lanStore.js b/src/renderer/src/features/lan/lanStore.js index 27fbae53..4f599ef1 100644 --- a/src/renderer/src/features/lan/lanStore.js +++ b/src/renderer/src/features/lan/lanStore.js @@ -56,9 +56,10 @@ export const useLanStore = defineStore('lan', { }, showPairing(view) { if (this.holdRequest(view)) return - if (view?.stage !== 'added') return (this.pairing = view) + const notice = { added: 'lan.add.added', 'added-back': 'lan.add.addedBack' }[view?.stage] + if (!notice) return (this.pairing = view) this.pairing = null - useDiffStore().showNotice(t('lan.add.added', { name: view.name })) + useDiffStore().showNotice(t(notice, { name: view.name })) }, async add({ fp, name }) { this.pairing = { role: 'adder', stage: 'connecting', fp, name } @@ -107,7 +108,7 @@ export const useLanStore = defineStore('lan', { this.bellOpen = false const res = await window.api.lanOpenItem(id) if (!res?.ok) return useDiffStore().showNotice(t('lan.items.gone')) - const tabId = openReceivedEntry(res.entry) + const tabId = openReceivedEntry(res.entry, res.from ?? item?.from) if (tabId) this.received = { ...this.received, diff --git a/src/shared/i18n/en-XA.json b/src/shared/i18n/en-XA.json index c633fba7..d4ccc864 100644 --- a/src/shared/i18n/en-XA.json +++ b/src/shared/i18n/en-XA.json @@ -2012,7 +2012,8 @@ "noCodeOnClipboard": "[Ţĥé çłĩƥƀōàřđ đōéşń’ţ ĥōłđ à ƥàĩřĩńğ çōđé. ·øé·øé·øé·øé·ø]", "add": "[Àđđ ·ø]", "button": "[Àđđ ·ø]", - "added": "[Àđđéđ {name} ·øé·]" + "added": "[Àđđéđ {name} ·øé·]", + "addedBack": "[{name} àđđéđ ŷōū ƀàçķ ·øé·øé·]" }, "code": { "title": "[{name} ŵàńţş ţō àđđ ŷōū ·øé·øé·]", diff --git a/src/shared/i18n/en.json b/src/shared/i18n/en.json index 1c2c7871..403ec263 100644 --- a/src/shared/i18n/en.json +++ b/src/shared/i18n/en.json @@ -2012,7 +2012,8 @@ "noCodeOnClipboard": "The clipboard doesn’t hold a pairing code.", "add": "Add", "button": "Add", - "added": "Added {name}" + "added": "Added {name}", + "addedBack": "{name} added you back" }, "code": { "title": "{name} wants to add you", diff --git a/tests/main/lan/pairing.test.js b/tests/main/lan/pairing.test.js index 0959d9ba..7f25c8b1 100644 --- a/tests/main/lan/pairing.test.js +++ b/tests/main/lan/pairing.test.js @@ -323,3 +323,12 @@ describe('when adding fails, the log says why', () => { expect(ben.logged.join('\n')).toMatch(/closed before/) }) }) + +describe('adding back', () => { + it('tells the holder they were added back when it already trusts the adder, with no new Add back', async () => { + const { ana, ben, started } = await startAdding({ isTrusted: async (fp) => fp === B }) + await ben.pairing.submitCode(started.id, ana.last().code) + await flush() + expect(ana.last()).toMatchObject({ stage: 'added-back', name: 'Ben', fp: B }) + }) +}) diff --git a/tests/renderer/composables/useSaveDiffTarget.test.js b/tests/renderer/composables/useSaveDiffTarget.test.js index 52762e56..36720f00 100644 --- a/tests/renderer/composables/useSaveDiffTarget.test.js +++ b/tests/renderer/composables/useSaveDiffTarget.test.js @@ -34,6 +34,13 @@ async function openSaved({ ttlHours = 1, tags = [] } = {}) { } describe('where a save lands', () => { + it('offers the tags the tab suggests, such as who sent it', () => { + const tabs = useTabsStore() + tabs.init() + tabs.active.suggestedTags = ['lan/ana'] + expect(useSaveDiffTarget().initial().tags).toEqual(['lan/ana']) + }) + it('offers the tour’s sample with the example tag', () => { const tabs = useTabsStore() tabs.init() diff --git a/tests/renderer/features/lan/itemActions.test.js b/tests/renderer/features/lan/itemActions.test.js index d8e97405..0035babd 100644 --- a/tests/renderer/features/lan/itemActions.test.js +++ b/tests/renderer/features/lan/itemActions.test.js @@ -2,10 +2,11 @@ import { describe, expect, it, vi } from 'vitest' const open = vi.fn(() => 'tab-d') const openSnippet = vi.fn(() => 'tab-s') +const tabs = [{ id: 'tab-d' }] vi.mock('../../../../src/renderer/src/stores/tabsStore', () => ({ - useTabsStore: () => ({ open, openSnippet }) + useTabsStore: () => ({ open, openSnippet, tabs }) })) -const { arePopupsShown, openReceivedEntry, withoutId } = +const { arePopupsShown, openReceivedEntry, receivedTag, withoutId } = await import('../../../../src/renderer/src/features/lan/itemActions') const { SILENCE_CHOICES, silenceLabelKey } = await import('../../../../src/renderer/src/features/lan/silenceChoices') @@ -47,6 +48,29 @@ describe('opening a received entry', () => { }) }) +describe('tagging what arrived on the network', () => { + it('nests the sender under lan', () => { + expect(receivedTag('Ana Petrauskė')).toBe('lan/ana petrauskė') + }) + + it('keeps a slash in the name from nesting deeper', () => { + expect(receivedTag('ops/infra laptop')).toBe('lan/ops-infra laptop') + }) + + it('adds the tag to a snippet beside its own tags', () => { + openReceivedEntry( + { kind: 'snippet', name: 'n', snippet: { content: '', tags: ['ops'] } }, + 'Ana' + ) + expect(openSnippet.mock.calls.at(-1)[0].initialTags).toEqual(['ops', 'lan/ana']) + }) + + it('suggests the tag when a diff is saved', () => { + openReceivedEntry({ kind: 'diff', name: 'cfg', snapshot: {} }, 'Ana') + expect(tabs[0].suggestedTags).toEqual(['lan/ana']) + }) +}) + describe('helpers', () => { it('shows popups only when on and not silenced', () => { expect(arePopupsShown({ popups: true, silencedUntil: 0 }, 10)).toBe(true)