Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(share): let the remembered channel survive the lists that load after it (#6295)

Louis Beaumont8c01e6d2d50f
diff --git a/apps/screenpipe-app-tauri/components/connected-share-dialog.test.tsx b/apps/screenpipe-app-tauri/components/connected-share-dialog.test.tsx
index 783ea2aee..7e987e4e2 100644
--- a/apps/screenpipe-app-tauri/components/connected-share-dialog.test.tsx
+++ b/apps/screenpipe-app-tauri/components/connected-share-dialog.test.tsx
@@ -4,7 +4,7 @@
import React from "react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ConnectedShareDialog } from "@/components/connected-share-dialog";
import type { ConnectedShareArtifact } from "@/lib/connected-share";
@@ -42,8 +42,39 @@ function jsonResponse(body: unknown, ok = true) {
return { ok, json: async () => body } as Response;
}
+/**
+ * A fresh remembered-destination store per test.
+ *
+ * The dialog writes where it last sent, so any test that completes a send
+ * leaves a destination behind for the next one. Under a runtime that really
+ * has `localStorage` that leak is real: a later test opening on a recalled
+ * destination instead of "choose where this goes" is the dialog behaving
+ * correctly and the suite lying about the starting state.
+ *
+ * It stayed hidden because the two runtimes disagree. The local runner has no
+ * `localStorage` at all, so recall silently no-ops and every test starts clean;
+ * CI has one, so state carries. Stubbing it here removes the divergence rather
+ * than papering over it: both runtimes now get the same empty store, and a
+ * test that wants a memory says so.
+ */
+const originalLocalStorage = Object.getOwnPropertyDescriptor(
+ window,
+ "localStorage",
+);
+let storageBacking = new Map<string, string>();
+
describe("ConnectedShareDialog", () => {
beforeEach(() => {
+ storageBacking = new Map();
+ Object.defineProperty(window, "localStorage", {
+ configurable: true,
+ value: {
+ getItem: (key: string) => storageBacking.get(key) ?? null,
+ setItem: (key: string, value: string) =>
+ void storageBacking.set(key, value),
+ removeItem: (key: string) => void storageBacking.delete(key),
+ } as Storage,
+ });
vi.clearAllMocks();
mocks.showChatWithPrefill.mockResolvedValue(undefined);
mocks.localFetch.mockImplementation(async (path: string) => {
@@ -77,6 +108,14 @@ describe("ConnectedShareDialog", () => {
});
});
+ afterEach(() => {
+ if (originalLocalStorage) {
+ Object.defineProperty(window, "localStorage", originalLocalStorage);
+ } else {
+ delete (window as { localStorage?: unknown }).localStorage;
+ }
+ });
+
// Destinations moved from seven always-visible tiles into one grouped menu,
// so choosing one is now: open the row, pick.
const openDestinations = async () => {
@@ -593,4 +632,137 @@ describe("ConnectedShareDialog", () => {
).toBeVisible();
});
});
+
+ /**
+ * The point of remembering is the second send, not the first.
+ *
+ * Recall is read when the connection check resolves, but the channel and team
+ * lists load after that and reset their own selection when they arrive. That
+ * ordering silently ate the remembered channel: the destination app came back
+ * but the channel fell to "my Slack messages" every time, so the weekly
+ * standup still had to be re-aimed. These assert on the request body rather
+ * than the label, because where the message actually lands is the thing that
+ * regressed.
+ */
+ describe("recall", () => {
+ const seedStorage = (value: unknown) => {
+ storageBacking.set(
+ "screenpipe.connected-share.last.meeting",
+ JSON.stringify(value),
+ );
+ };
+
+ const sendBody = () => {
+ const call = mocks.localFetch.mock.calls.find(
+ ([path]) => path === "/connections/slack/send",
+ );
+ return JSON.parse(call?.[1]?.body as string);
+ };
+
+ it("sends to the remembered channel without asking again", async () => {
+ seedStorage({ destination: "slack", target: "C1", instance: "acme" });
+ render(
+ <ConnectedShareDialog open onOpenChange={vi.fn()} artifact={artifact} />,
+ );
+
+ // No destination pick and no channel pick: recall answered both.
+ const confirm = await screen.findByTestId("connected-share-confirm");
+ await waitFor(() =>
+ expect(
+ mocks.localFetch.mock.calls.some(([path]) =>
+ String(path).startsWith("/connections/slack/conversations"),
+ ),
+ ).toBe(true),
+ );
+ fireEvent.click(confirm);
+
+ await screen.findByText("sent to Slack");
+ expect(sendBody()).toMatchObject({ channel: "C1", instance: "acme" });
+ });
+
+ it("falls back to the private self-send when the channel is gone", async () => {
+ // Remembered a channel this account can no longer see. Leaving it
+ // selected would fail at send time; dropping it silently is the honest
+ // outcome, because a self-send cannot leak into the wrong room.
+ seedStorage({ destination: "slack", target: "C-deleted" });
+ render(
+ <ConnectedShareDialog open onOpenChange={vi.fn()} artifact={artifact} />,
+ );
+
+ const confirm = await screen.findByTestId("connected-share-confirm");
+ await waitFor(() =>
+ expect(
+ mocks.localFetch.mock.calls.some(([path]) =>
+ String(path).startsWith("/connections/slack/conversations"),
+ ),
+ ).toBe(true),
+ );
+ fireEvent.click(confirm);
+
+ await screen.findByText("sent to Slack");
+ expect(sendBody()).not.toHaveProperty("channel");
+ });
+
+ it("does not aim a recalled channel at a destination the user re-picked", async () => {
+ // Slack is remembered but no longer connected, so the destination falls
+ // back to a question. The stale channel must not survive that.
+ seedStorage({ destination: "slack", target: "C1" });
+ mocks.localFetch.mockImplementation(
+ async (path: string, init?: RequestInit) => {
+ if (path === "/connections") {
+ return jsonResponse({
+ data: [
+ { id: "slack", connected: false },
+ { id: "linear", connected: true },
+ ],
+ });
+ }
+ if (path === "/connections/linear/proxy/graphql") {
+ const body = JSON.parse((init as RequestInit)?.body as string);
+ if (body?.variables?.input) {
+ return jsonResponse({
+ data: {
+ issueCreate: {
+ success: true,
+ issue: { id: "i1", identifier: "COR-1", title: "Roadmap" },
+ },
+ },
+ });
+ }
+ return jsonResponse({
+ data: { teams: { nodes: [{ id: "T1", name: "Core", key: "COR" }] } },
+ });
+ }
+ throw new Error(`unexpected request: ${path}`);
+ },
+ );
+
+ render(
+ <ConnectedShareDialog open onOpenChange={vi.fn()} artifact={artifact} />,
+ );
+
+ await openDestinations();
+ fireEvent.click(
+ await screen.findByTestId("connected-share-destination-linear"),
+ );
+ await waitFor(() =>
+ expect(
+ mocks.localFetch.mock.calls.some(
+ ([path]) => path === "/connections/linear/proxy/graphql",
+ ),
+ ).toBe(true),
+ );
+ fireEvent.click(await screen.findByTestId("connected-share-confirm"));
+
+ // The team list chose its own first team; the Slack channel id never
+ // leaked across into the issue.
+ await waitFor(() => {
+ const create = mocks.localFetch.mock.calls
+ .filter(([path]) => path === "/connections/linear/proxy/graphql")
+ .map(([, init]) => JSON.parse((init as RequestInit)?.body as string))
+ .find((body) => body?.variables?.input);
+ expect(create?.variables.input.teamId).toBe("T1");
+ });
+ });
+ });
});
diff --git a/apps/screenpipe-app-tauri/components/connected-share-dialog.tsx b/apps/screenpipe-app-tauri/components/connected-share-dialog.tsx
index fd72bd39d..79698a683 100644
--- a/apps/screenpipe-app-tauri/components/connected-share-dialog.tsx
+++ b/apps/screenpipe-app-tauri/components/connected-share-dialog.tsx
@@ -8,6 +8,7 @@ import React, {
useEffect,
useLayoutEffect,
useMemo,
+ useRef,
useState,
} from "react";
import {
@@ -65,6 +66,7 @@ import {
preferredShareDestination,
readRememberedShare,
writeRememberedShare,
+ type RememberedShare,
} from "@/lib/connected-share-preference";
import { showChatWithPrefill } from "@/lib/chat-utils";
@@ -266,6 +268,50 @@ export function ConnectedShareDialog({
const [linearTeamId, setLinearTeamId] = useState("");
const [linearTitle, setLinearTitle] = useState(artifact.title);
+ /**
+ * The remembered destination, held until the list that owns it has loaded.
+ *
+ * Recall has to survive the two fetches that follow it. Both the Slack
+ * channel list and the Linear team list reset their own selection when they
+ * resolve — correctly, because switching workspace must not keep a channel
+ * from the previous one — and that reset used to land *after* the remembered
+ * target was restored, throwing it away before the user ever saw it. Only the
+ * destination app survived, so the weekly standup still had to re-pick its
+ * channel every time.
+ *
+ * Parking it in a ref lets each list claim its own value exactly once, after
+ * it can check the value still exists. A later switch by the user finds the
+ * recall already spent and resets as before.
+ */
+ const pendingRecallRef = useRef<RememberedShare | null>(null);
+
+ /**
+ * Claim the remembered target for a destination, once.
+ *
+ * Gated on the destination matching because `target` holds a Slack channel or
+ * a Linear team depending on where the last send went; a channel id must not
+ * be offered to the team list. Consumed even when it turns out to be stale so
+ * a failed match is not retried on the next reload.
+ */
+ const claimRecalledTarget = useCallback(
+ (forDestination: Destination): string | null => {
+ const pending = pendingRecallRef.current;
+ if (!pending?.target || pending.destination !== forDestination) {
+ return null;
+ }
+ pendingRecallRef.current = { ...pending, target: undefined };
+ return pending.target;
+ },
+ [],
+ );
+
+ const claimRecalledInstance = useCallback((): string | null => {
+ const pending = pendingRecallRef.current;
+ if (!pending?.instance) return null;
+ pendingRecallRef.current = { ...pending, instance: undefined };
+ return pending.instance;
+ }, []);
+
const resetPreview = useCallback(
(ids: string[]) => {
const rendered = renderConnectedShareArtifact(artifact, ids);
@@ -284,6 +330,7 @@ export function ConnectedShareDialog({
useEffect(() => {
if (!open) return;
+ pendingRecallRef.current = null;
resetPreview(allSectionIds);
setLinearTitle(artifact.title);
// Stays null until the connection check says what is actually reachable.
@@ -350,10 +397,21 @@ export function ConnectedShareDialog({
...(ready.chat.linear ? ["chat-linear"] : []),
...(ready.chat.notion ? ["chat-notion"] : []),
];
- setDestination(
- preferredShareDestination(remembered, connected) as Destination | null,
- );
- if (remembered?.target) setSlackTarget(remembered.target);
+ const nextDestination = preferredShareDestination(
+ remembered,
+ connected,
+ ) as Destination | null;
+ setDestination(nextDestination);
+ // Park the rest of the recall for the channel and team lists to claim
+ // once they can confirm the remembered value still exists. Dropped when
+ // the destination is gone, so a revoked Slack connection cannot leave a
+ // channel selected under a destination the user has to re-pick anyway.
+ pendingRecallRef.current =
+ remembered && nextDestination === remembered.destination
+ ? remembered
+ : null;
+ // The workspace is safe to apply now: it decides which channel list is
+ // fetched, so waiting would fetch the wrong workspace and refetch.
if (remembered?.instance) setSlackInstance(remembered.instance);
})
.catch((error) => {
@@ -401,20 +459,36 @@ export function ConnectedShareDialog({
}));
if (cancelled) return;
setSlackInstances(instances);
- setSlackInstance(instances[0]?.instance ?? DEFAULT_SLACK_INSTANCE);
+ // Keep the remembered workspace when it is still connected; a stale one
+ // falls back to the first rather than selecting nothing.
+ const recalled = claimRecalledInstance();
+ const stillConnected =
+ recalled !== null &&
+ instances.some(
+ (entry) => (entry.instance ?? DEFAULT_SLACK_INSTANCE) === recalled,
+ );
+ setSlackInstance(
+ stillConnected
+ ? recalled
+ : (instances[0]?.instance ?? DEFAULT_SLACK_INSTANCE),
+ );
})
.catch(() => undefined);
return () => {
cancelled = true;
};
- }, [availability.direct.slack, open]);
+ }, [availability.direct.slack, claimRecalledInstance, open]);
useEffect(() => {
if (!open || !availability.direct.slack || destination !== "slack") return;
let cancelled = false;
setSlackChannelsLoading(true);
setSlackChannelsError(null);
- setSlackTarget(SELF_SLACK_TARGET);
+ // Clear the selection while the list reloads, so a channel from the
+ // workspace being switched away from cannot stay selected. Held back when a
+ // recall is still pending: that one is applied below, once it can be
+ // checked against the channels that actually came back.
+ if (!pendingRecallRef.current?.target) setSlackTarget(SELF_SLACK_TARGET);
const instanceQuery =
slackInstance !== DEFAULT_SLACK_INSTANCE
? `&instance=${encodeURIComponent(slackInstance)}`
@@ -442,11 +516,27 @@ export function ConnectedShareDialog({
})) as SlackChannel[];
})
.then((channels) => {
- if (!cancelled) setSlackChannels(channels);
+ if (cancelled) return;
+ setSlackChannels(channels);
+ // A remembered channel is only restored once the list proves it is
+ // still there. A deleted or now-inaccessible channel falls back to the
+ // private self-send rather than sitting selected and failing on send.
+ const recalled = claimRecalledTarget("slack");
+ if (recalled) {
+ setSlackTarget(
+ channels.some((channel) => channel.id === recalled)
+ ? recalled
+ : SELF_SLACK_TARGET,
+ );
+ }
})
.catch((error) => {
if (cancelled) return;
setSlackChannels([]);
+ // The recall cannot be checked against a list that failed to load, so
+ // spend it and fall back rather than leaving a channel selected that
+ // may no longer exist.
+ if (claimRecalledTarget("slack")) setSlackTarget(SELF_SLACK_TARGET);
setSlackChannelsError(
error instanceof Error
? error.message
@@ -461,6 +551,7 @@ export function ConnectedShareDialog({
};
}, [
availability.direct.slack,
+ claimRecalledTarget,
destination,
open,
slackInstance,
@@ -490,7 +581,12 @@ export function ConnectedShareDialog({
.then((teams) => {
if (cancelled) return;
setLinearTeams(teams);
- setLinearTeamId(teams[0]?.id ?? "");
+ // Same rule as the Slack channel: the remembered team is used only if
+ // it is still in the list this account can see.
+ const recalled = claimRecalledTarget("linear");
+ const stillVisible =
+ recalled !== null && teams.some((team) => team.id === recalled);
+ setLinearTeamId(stillVisible ? recalled : (teams[0]?.id ?? ""));
})
.catch((error) => {
if (cancelled) return;
@@ -508,7 +604,13 @@ export function ConnectedShareDialog({
return () => {
cancelled = true;
};
- }, [availability.direct.linear, destination, linearRefresh, open]);
+ }, [
+ availability.direct.linear,
+ claimRecalledTarget,
+ destination,
+ linearRefresh,
+ open,
+ ]);
const setSectionChecked = (id: string, checked: boolean) => {
const next = checked