Skip to content

Open-Source API Development Ecosystem • https://hoppscotch.io • Offline, On-Prem & Cloud • Web, Desktop & CLI • Open-Source Alternative to Postman, Insomnia

fix(common): preserve request tab description on documentation save (#6592)

Nivedin469c90234af4
diff --git a/packages/hoppscotch-common/src/components/collections/SaveRequest.vue b/packages/hoppscotch-common/src/components/collections/SaveRequest.vue
index cc41478b8..cd9f99106 100644
--- a/packages/hoppscotch-common/src/components/collections/SaveRequest.vue
+++ b/packages/hoppscotch-common/src/components/collections/SaveRequest.vue
@@ -122,6 +122,7 @@ import { useToast } from "@composables/toast"
import {
HoppGQLRequest,
HoppRESTRequest,
+ generateUniqueRefId,
isHoppRESTRequest,
} from "@hoppscotch/data"
import { computedWithControl } from "@vueuse/core"
@@ -144,6 +145,8 @@ import {
cascadeParentCollectionForProperties,
editGraphqlRequest,
editRESTRequest,
+ navigateToFolderWithIndexPath,
+ restCollectionStore,
saveGraphqlRequestAs,
saveRESTRequestAs,
} from "~/newstore/collections"
@@ -338,6 +341,18 @@ const saveRequestAs = async () => {
requestUpdated.name = requestName.value
+ // A copy is a new entry and needs its own `_ref_id` — equal ref ids are
+ // treated as the same request, which would bind the copy's tab to the source
+ if (
+ isHoppRESTRequest(requestUpdated) &&
+ (picked.value.pickedType === "my-collection" ||
+ picked.value.pickedType === "my-folder" ||
+ picked.value.pickedType === "teams-collection" ||
+ picked.value.pickedType === "teams-folder")
+ ) {
+ requestUpdated._ref_id = generateUniqueRefId("req")
+ }
+
if (picked.value.pickedType === "my-collection") {
if (!isHoppRESTRequest(requestUpdated))
throw new Error("requestUpdated is not a REST Request")
@@ -412,6 +427,28 @@ const saveRequestAs = async () => {
if (!isHoppRESTRequest(requestUpdated))
throw new Error("requestUpdated is not a REST Request")
+ // Overwriting replaces the target's content, not its identity — keep the
+ // target's own `_ref_id` and backend `id` so its tabs stay bound to it and
+ // the source doesn't share identity with the copy
+ const targetRequest = navigateToFolderWithIndexPath(
+ restCollectionStore.value.state,
+ picked.value.folderPath.split("/").map((x) => parseInt(x))
+ )?.requests[picked.value.requestIndex]
+
+ // Delete rather than assign undefined — an explicit undefined key survives
+ // into the store and not every sync backend tolerates it
+ if (targetRequest && "_ref_id" in targetRequest && targetRequest._ref_id) {
+ requestUpdated._ref_id = targetRequest._ref_id
+ } else {
+ delete requestUpdated._ref_id
+ }
+
+ if (targetRequest?.id) {
+ requestUpdated.id = targetRequest.id
+ } else {
+ delete requestUpdated.id
+ }
+
editRESTRequest(
picked.value.folderPath,
picked.value.requestIndex,
@@ -426,6 +463,7 @@ const saveRequestAs = async () => {
originLocation: "user-collection",
folderPath: picked.value.folderPath,
requestIndex: picked.value.requestIndex,
+ requestRefID: requestUpdated._ref_id ?? requestUpdated.id,
},
}
diff --git a/packages/hoppscotch-common/src/components/collections/documentation/index.vue b/packages/hoppscotch-common/src/components/collections/documentation/index.vue
index 16dfdf72b..49f23bd09 100644
--- a/packages/hoppscotch-common/src/components/collections/documentation/index.vue
+++ b/packages/hoppscotch-common/src/components/collections/documentation/index.vue
@@ -278,6 +278,8 @@ import {
} from "~/helpers/backend/helpers"
import { GQLError } from "~/helpers/backend/GQLClient"
import { getErrorMessage } from "~/helpers/backend/mutations/MockServer"
+import { HoppRESTSaveContext } from "~/helpers/rest/document"
+import { RESTTabService } from "~/services/tab/rest"
import {
DocumentationService,
@@ -342,6 +344,35 @@ const props = withDefaults(
)
const documentationService = useService(DocumentationService)
+const restTabs = useService(RESTTabService)
+
+/**
+ * Mirrors a saved documentation description onto any open tabs of the request —
+ * otherwise a tab keeps its pre-edit copy and its next save writes the stale
+ * description back over the one just saved.
+ */
+const syncOpenRequestTabDescription = (
+ saveContext: HoppRESTSaveContext,
+ description: string
+) => {
+ const possibleTabs = restTabs.getTabsRefWithSaveContext(saveContext)
+
+ for (const possibleTab of possibleTabs) {
+ // Hold the document, not the tab ref — the ref's getter throws once the
+ // tab is closed, and it's read again after a tick
+ const tabDocument = possibleTab.value.document
+
+ if (tabDocument.type !== "request") continue
+
+ const wasDirty = tabDocument.isDirty
+ tabDocument.request.description = description
+
+ // The tab marks itself dirty on any request change; restore its prior state
+ nextTick(() => {
+ tabDocument.isDirty = wasDirty
+ })
+ }
+}
const isLoadingTeamCollection = ref<boolean>(false)
const isSavingDocumentation = ref<boolean>(false)
@@ -774,9 +805,13 @@ const saveCollectionDocumentation = async () => {
}
const saveRequestDocumentation = async () => {
+ // The editor stays live while the team mutation is in flight — sync the tab
+ // with what was persisted, not whatever the editor holds when it resolves
+ const savedDescription = documentationDescription.value
+
const updatedRequest = {
...props.request!,
- description: documentationDescription.value,
+ description: savedDescription,
}
if (props.isTeamCollection && props.requestID) {
@@ -796,6 +831,13 @@ const saveRequestDocumentation = async () => {
isSavingDocumentation.value = false
},
() => {
+ syncOpenRequestTabDescription(
+ {
+ originLocation: "team-collection",
+ requestID: props.requestID!,
+ },
+ savedDescription
+ )
toast.success(t("documentation.save_success"))
isSavingDocumentation.value = false
}
@@ -804,6 +846,15 @@ const saveRequestDocumentation = async () => {
} else {
// Personal request
editRESTRequest(props.folderPath!, props.requestIndex!, updatedRequest)
+ syncOpenRequestTabDescription(
+ {
+ originLocation: "user-collection",
+ folderPath: props.folderPath!,
+ requestIndex: props.requestIndex!,
+ requestRefID: updatedRequest._ref_id ?? updatedRequest.id,
+ },
+ savedDescription
+ )
toast.success(t("documentation.save_success"))
}
}
@@ -916,6 +967,13 @@ const saveRequestDocumentationById = async (
return false
},
() => {
+ syncOpenRequestTabDescription(
+ {
+ originLocation: "team-collection",
+ requestID: item.requestID!,
+ },
+ documentation
+ )
return true
}
)
@@ -939,6 +997,15 @@ const saveRequestDocumentationById = async (
try {
editRESTRequest(folderPath, item.requestIndex, updatedRequest)
+ syncOpenRequestTabDescription(
+ {
+ originLocation: "user-collection",
+ folderPath,
+ requestIndex: item.requestIndex,
+ requestRefID: updatedRequest._ref_id ?? updatedRequest.id,
+ },
+ documentation
+ )
return true
} catch (e) {
console.error(e)
diff --git a/packages/hoppscotch-common/src/helpers/import-export/import/index.ts b/packages/hoppscotch-common/src/helpers/import-export/import/index.ts
index 66c1ad1d1..2783d1503 100644
--- a/packages/hoppscotch-common/src/helpers/import-export/import/index.ts
+++ b/packages/hoppscotch-common/src/helpers/import-export/import/index.ts
@@ -3,6 +3,7 @@ import type { Component } from "vue"
import { StepsOutputList } from "../steps"
import {
HoppCollection,
+ generateUniqueRefId,
makeCollection,
translateToNewRESTCollection,
} from "@hoppscotch/data"
@@ -91,6 +92,13 @@ export const sanitizeCollection = (
return makeCollection({
...rest,
+ // Requests carry identity too — an imported file may hold `_ref_id`/`id`
+ // values that already exist in the workspace, and matching treats equal
+ // identities as the same request
+ requests: rest.requests.map((request) => {
+ const { id: _requestId, ...requestRest } = request
+ return { ...requestRest, _ref_id: generateUniqueRefId("req") }
+ }),
folders: rest.folders.map(sanitizeCollection),
})
}
diff --git a/packages/hoppscotch-common/src/newstore/collections.ts b/packages/hoppscotch-common/src/newstore/collections.ts
index a6c2bec3b..38dbdc80b 100644
--- a/packages/hoppscotch-common/src/newstore/collections.ts
+++ b/packages/hoppscotch-common/src/newstore/collections.ts
@@ -730,6 +730,16 @@ const restCollectionDispatchers = defineDispatchers({
_ref_id: generateUniqueRefId("coll"),
}
+ // Copied requests need their own identity too — matching falls back to
+ // the backend `id`, so even a legacy request copied without a fresh
+ // `_ref_id` would fight the original for tabs
+ newCollection.requests = (newCollection.requests ?? []).map(
+ (request) => ({
+ ...request,
+ _ref_id: generateUniqueRefId("req"),
+ })
+ )
+
newCollection.folders = (newCollection.folders ?? []).map((folder) =>
recursiveChangeRefIdToAvoidConflicts(folder)
)
@@ -1446,6 +1456,13 @@ const gqlCollectionDispatchers = defineDispatchers({
...coll,
_ref_id: generateUniqueRefId("coll"),
}
+
+ // Copied requests need fresh `_ref_id`s too, else they alias the originals' tabs
+ next.requests = (next.requests ?? []).map((request) => ({
+ ...request,
+ _ref_id: generateUniqueRefId("req"),
+ }))
+
next.folders = (next.folders ?? []).map(
recursiveChangeRefIdToAvoidConflicts
)
diff --git a/packages/hoppscotch-common/src/pages/import.vue b/packages/hoppscotch-common/src/pages/import.vue
index 851fa1cbe..3bab15364 100644
--- a/packages/hoppscotch-common/src/pages/import.vue
+++ b/packages/hoppscotch-common/src/pages/import.vue
@@ -21,7 +21,10 @@ import {
} from "~/helpers/clientLocalVariables"
import { useI18n } from "@composables/i18n"
import { useToast } from "@composables/toast"
-import { IMPORTER_INVALID_FILE_FORMAT } from "~/helpers/import-export/import"
+import {
+ IMPORTER_INVALID_FILE_FORMAT,
+ sanitizeCollection,
+} from "~/helpers/import-export/import"
import { OPENAPI_DEREF_ERROR } from "~/helpers/import-export/import/openapi"
import { isOfType } from "~/helpers/functional/primtive"
import { TELeftType } from "~/helpers/functional/taskEither"
@@ -116,10 +119,11 @@ const handleImportFailure = (error: ImportCollectionsError) => {
}
const handleImportSuccess = (collections: HoppCollection[]) => {
- // Mirror the modal-import path: stamp `_ref_id`s, persist any raw
- // secret values to the local secret store, then append the stripped
- // tree to newstore so localStorage / future syncs stay clean.
- const withRefIds = collections.map(ensureRefIds)
+ // Mirror the modal-import path: sanitize file-carried identities, stamp
+ // `_ref_id`s, persist any raw secret values to the local secret store, then
+ // append the stripped tree to newstore so localStorage / future syncs stay
+ // clean.
+ const withRefIds = collections.map(sanitizeCollection).map(ensureRefIds)
withRefIds.forEach(populateLocalStoresFromCollectionTree)
appendRESTCollections(withRefIds.map(stripCollectionTreeForStore))
diff --git a/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.ts b/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.ts
index d0884a4fa..63a31ffde 100644
--- a/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.ts
+++ b/packages/hoppscotch-common/src/services/spotlight/searchers/collections.searcher.ts
@@ -6,6 +6,7 @@ import {
SpotlightSearcherSessionState,
SpotlightService,
} from "../"
+import { cloneDeep } from "lodash-es"
import { Ref, computed, effectScope, markRaw, ref, watch } from "vue"
import { getI18n } from "~/modules/i18n"
import MiniSearch from "minisearch"
@@ -304,32 +305,35 @@ export class CollectionsSpotlightSearcherService
})
}
- const possibleTab = this.restTab.getTabRefWithSaveContext({
+ const resolvedFolderPath = folderPath.join("/")
+
+ const req = this.getRESTFolderFromFolderPath(resolvedFolderPath)
+ ?.requests[reqIndex] as HoppRESTRequest
+
+ if (!req) return
+
+ // Record `requestRefID` like the sidebar does — a tab opened without one
+ // isn't matched by lookups that supply it, and the request opens twice
+ const saveContext = {
originLocation: "user-collection",
- folderPath: folderPath.join("/"),
+ folderPath: resolvedFolderPath,
requestIndex: reqIndex,
- })
+ requestRefID: req._ref_id ?? req.id,
+ } as const
+
+ const possibleTab = this.restTab.getTabRefWithSaveContext(saveContext)
if (possibleTab) {
this.restTab.setActiveTab(possibleTab.value.id)
} else {
- const req = this.getRESTFolderFromFolderPath(folderPath.join("/"))
- ?.requests[reqIndex] as HoppRESTRequest
-
- if (!req) return
-
this.restTab.createNewTab(
{
type: "request",
- request: req,
+ request: cloneDeep(req),
isDirty: false,
- saveContext: {
- originLocation: "user-collection",
- folderPath: folderPath.join("/"),
- requestIndex: reqIndex,
- },
+ saveContext,
inheritedProperties: cascadeParentCollectionForProperties(
- folderPath.join("/"),
+ resolvedFolderPath,
"rest"
),
},
@@ -352,7 +356,7 @@ export class CollectionsSpotlightSearcherService
requestIndex: reqIndex,
},
cursorPosition: 0,
- request: req,
+ request: cloneDeep(req),
isDirty: false,
inheritedProperties: cascadeParentCollectionForProperties(
folderPath.join("/"),
diff --git a/packages/hoppscotch-common/src/services/tab/__tests__/rest-tab.service.spec.ts b/packages/hoppscotch-common/src/services/tab/__tests__/rest-tab.service.spec.ts
new file mode 100644
index 000000000..f0b080d9d
--- /dev/null
+++ b/packages/hoppscotch-common/src/services/tab/__tests__/rest-tab.service.spec.ts
@@ -0,0 +1,339 @@
+import { describe, expect, it, vi } from "vitest"
+import { TestContainer } from "dioc/testing"
+
+import { getDefaultRESTRequest } from "~/helpers/rest/default"
+import { HoppRESTSaveContext } from "~/helpers/rest/document"
+import { RESTTabService } from "../rest"
+
+// The persistence import drags in stores with top-level side effects that
+// can't run in this bare container; matching never touches it (hoisted mock)
+vi.mock("../../persistence", () => ({
+ PersistenceService: class {},
+ STORE_KEYS: {},
+}))
+
+const makeService = () => {
+ const container = new TestContainer()
+ return container.bind(RESTTabService)
+}
+
+const openRequestTab = (
+ service: RESTTabService,
+ saveContext: HoppRESTSaveContext,
+ requestFields?: { _ref_id?: string; id?: string }
+) =>
+ service.createNewTab({
+ type: "request",
+ request: { ...getDefaultRESTRequest(), ...requestFields },
+ isDirty: false,
+ saveContext,
+ })
+
+describe("RESTTabService", () => {
+ describe("getTabRefWithSaveContext", () => {
+ it("matches positionally when neither side has a requestRefID", () => {
+ const service = makeService()
+
+ const tab = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ })
+
+ const found = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ })
+
+ expect(found?.value.id).toEqual(tab.id)
+ })
+
+ it("does not match a different position when neither side has a requestRefID", () => {
+ const service = makeService()
+
+ openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ })
+
+ expect(
+ service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 0,
+ })
+ ).toBeNull()
+ })
+
+ it("matches on requestRefID even when the tab's index has drifted", () => {
+ const service = makeService()
+
+ const tab = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "req_a",
+ })
+
+ const found = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 0,
+ requestRefID: "req_a",
+ })
+
+ expect(found?.value.id).toEqual(tab.id)
+ })
+
+ it("does not match a tab holding a different request at the same position", () => {
+ const service = makeService()
+
+ openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 0,
+ requestRefID: "req_other",
+ })
+
+ expect(
+ service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 0,
+ requestRefID: "req_a",
+ })
+ ).toBeNull()
+ })
+
+ it("does not match an identity-less tab when the lookup names its request", () => {
+ const service = makeService()
+
+ openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ })
+
+ expect(
+ service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "req_a",
+ })
+ ).toBeNull()
+ })
+
+ it("identifies a tab without a context ref by the request it holds", () => {
+ const service = makeService()
+
+ // Context predates ref ids, but the held request names itself — found
+ // even though its index has drifted
+ const tab = openRequestTab(
+ service,
+ {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 5,
+ },
+ { _ref_id: "req_a" }
+ )
+
+ const found = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "req_a",
+ })
+
+ expect(found?.value.id).toEqual(tab.id)
+ })
+
+ it("identifies a legacy tab by the backend id its request holds", () => {
+ const service = makeService()
+
+ const tab = openRequestTab(
+ service,
+ {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 3,
+ },
+ { id: "backend_1" }
+ )
+
+ const found = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "backend_1",
+ })
+
+ expect(found?.value.id).toEqual(tab.id)
+ })
+
+ it("rejects a stale tab holding a different request at reused coordinates", () => {
+ const service = makeService()
+
+ openRequestTab(
+ service,
+ {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ },
+ { _ref_id: "req_other" }
+ )
+
+ expect(
+ service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "req_a",
+ })
+ ).toBeNull()
+ })
+
+ it("falls back to position when the lookup has no requestRefID but the tab does", () => {
+ const service = makeService()
+
+ const tab = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "req_a",
+ })
+
+ const found = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ })
+
+ expect(found?.value.id).toEqual(tab.id)
+ })
+
+ it("treats an empty-string requestRefID as missing on both sides", () => {
+ const service = makeService()
+
+ // Some creation paths store "" when a request has neither `_ref_id` nor `id`
+ const tab = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "",
+ })
+
+ const found = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "",
+ })
+
+ expect(found?.value.id).toEqual(tab.id)
+ })
+
+ it("scopes example lookups by exampleID", () => {
+ const service = makeService()
+
+ const requestTab = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ })
+
+ const exampleTab = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ exampleID: "0",
+ })
+
+ const foundRequest = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ })
+
+ const foundExample = service.getTabRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ exampleID: "0",
+ })
+
+ expect(foundRequest?.value.id).toEqual(requestTab.id)
+ expect(foundExample?.value.id).toEqual(exampleTab.id)
+ })
+
+ it("matches team tabs by requestID and exampleID", () => {
+ const service = makeService()
+
+ const tab = openRequestTab(service, {
+ originLocation: "team-collection",
+ requestID: "team_req_1",
+ })
+
+ const found = service.getTabRefWithSaveContext({
+ originLocation: "team-collection",
+ requestID: "team_req_1",
+ })
+
+ expect(found?.value.id).toEqual(tab.id)
+
+ expect(
+ service.getTabRefWithSaveContext({
+ originLocation: "team-collection",
+ requestID: "team_req_1",
+ exampleID: "0",
+ })
+ ).toBeNull()
+ })
+ })
+
+ describe("getTabsRefWithSaveContext", () => {
+ it("returns every tab matching the save context", () => {
+ const service = makeService()
+
+ const first = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "req_a",
+ })
+
+ // A duplicate of the same request whose index has drifted
+ const second = openRequestTab(service, {
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 0,
+ requestRefID: "req_a",
+ })
+
+ const found = service.getTabsRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 1,
+ requestRefID: "req_a",
+ })
+
+ expect(found.map((tab) => tab.value.id)).toEqual([first.id, second.id])
+ })
+
+ it("returns an empty array when nothing matches", () => {
+ const service = makeService()
+
+ expect(
+ service.getTabsRefWithSaveContext({
+ originLocation: "user-collection",
+ folderPath: "0",
+ requestIndex: 0,
+ })
+ ).toEqual([])
+ })
+ })
+})
diff --git a/packages/hoppscotch-common/src/services/tab/rest.ts b/packages/hoppscotch-common/src/services/tab/rest.ts
index 35e50d204..884491e71 100644
--- a/packages/hoppscotch-common/src/services/tab/rest.ts
+++ b/packages/hoppscotch-common/src/services/tab/rest.ts
@@ -5,7 +5,7 @@ import { HoppRESTSaveContext, HoppTabDocument } from "~/helpers/rest/document"
import { getService } from "~/modules/dioc"
import { PersistenceService, STORE_KEYS } from "../persistence"
import { TabService } from "./tab"
-import { PersistableTabState } from "."
+import { HoppTab, PersistableTabState } from "."
export class RESTTabService extends TabService<HoppTabDocument> {
public static readonly ID = "REST_TAB_SERVICE"
@@ -70,30 +70,63 @@ export class RESTTabService extends TabService<HoppTabDocument> {
return savedState
}
+ private matchesSaveContext(
+ tab: HoppTab<HoppTabDocument>,
+ ctx: HoppRESTSaveContext
+ ) {
+ if (tab.document.type === "test-runner") return false
+
+ // For `team-collection` request id can be considered unique
+ if (ctx?.originLocation === "team-collection") {
+ return (
+ tab.document.saveContext?.originLocation === "team-collection" &&
+ tab.document.saveContext.requestID === ctx.requestID &&
+ tab.document.saveContext.exampleID === ctx.exampleID
+ )
+ }
+
+ const tabCtx = tab.document.saveContext
+
+ if (tabCtx?.originLocation !== "user-collection") return false
+ if (tabCtx.exampleID !== ctx?.exampleID) return false
+
+ // A tab whose context predates ref ids is still identified by the request
+ // it holds. Truthiness, not a null check: some creation paths store `""`,
+ // which is not an identity.
+ const tabRefID =
+ tabCtx.requestRefID ||
+ (tab.document.type === "request"
+ ? tab.document.request._ref_id || tab.document.request.id
+ : undefined)
+
+ // A lookup that names its request is authoritative — a tab with a
+ // different or missing identity is not that request, even at matching
+ // coordinates, which may have been reused since the tab was bound.
+ if (ctx?.requestRefID) {
+ return tabRefID === ctx.requestRefID
+ }
+
+ // Position is all that's left when the lookup carries no identity
+ return (
+ tabCtx.folderPath === ctx?.folderPath &&
+ tabCtx.requestIndex === ctx?.requestIndex
+ )
+ }
+
+ /**
+ * Returns every tab matching the save context — a request can be open in
+ * more than one tab, and a write-back that skips one leaves it holding
+ * stale content that its next save persists.
+ */
+ public getTabsRefWithSaveContext(ctx: HoppRESTSaveContext) {
+ return Array.from(this.tabMap.values())
+ .filter((tab) => this.matchesSaveContext(tab, ctx))
+ .map((tab) => this.getTabRef(tab.id))
+ }
+
public getTabRefWithSaveContext(ctx: HoppRESTSaveContext) {
for (const tab of this.tabMap.values()) {
- // For `team-collection` request id can be considered unique
- if (tab.document.type === "test-runner") continue
-
- if (ctx?.originLocation === "team-collection") {
- if (
- tab.document.saveContext?.originLocation === "team-collection" &&
- tab.document.saveContext.requestID === ctx.requestID &&
- tab.document.saveContext.exampleID === ctx.exampleID
- ) {
- return this.getTabRef(tab.id)
- }
- } else if (
- tab.document.saveContext?.originLocation === "user-collection" &&
- tab.document.saveContext.folderPath === ctx?.folderPath &&
- tab.document.saveContext.requestIndex === ctx?.requestIndex &&
- tab.document.saveContext.exampleID === ctx?.exampleID &&
- (ctx?.requestRefID != null
- ? tab.document.saveContext.requestRefID === ctx.requestRefID
- : true)
- ) {
- return this.getTabRef(tab.id)
- }
+ if (this.matchesSaveContext(tab, ctx)) return this.getTabRef(tab.id)
}
return null