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
43 changes: 43 additions & 0 deletions Tests/StackNudgePanelCoreTests/ExtensionHostServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -498,6 +498,49 @@ final class ExtensionHostServiceTests: XCTestCase {
XCTAssertEqual(host.services, [:])
}

// MARK: - Feed

// A feed event goes to the app with the extension's id and name, a
// retract with its key, and an action on one goes back only while it runs.
func testAFeedEventReachesTheAppAndItsActionComesBack() {
tiers = ["exchange": .service]
let host = host()
var posted: [(String, String, ServiceProtocol.FeedPost)] = []
var retracted: [(String, String)] = []
host.onFeed = { posted.append(($0, $1, $2)) }
host.onRetract = { retracted.append(($0, $1)) }
host.load(.init(installed: [manifest("exchange", capabilities: ["feed"])]))
XCTAssertFalse(host.performFeedAction(FeedAction(id: "send", label: "Send"), key: "draft-1", on: "exchange"),
"nothing is running to take it yet")
spawner.last.ready()
spawner.last.say(#"{"type":"feed","event":{"title":"Reply","key":"draft-1","action":{"id":"send","label":"Send"}}}"#)
spawner.last.say(#"{"type":"retract","key":"draft-0"}"#)
XCTAssertEqual(posted.map(\.0), ["exchange"])
XCTAssertEqual(posted.first?.1, "exchange")
XCTAssertEqual(posted.first?.2.action, FeedAction(id: "send", label: "Send"))
XCTAssertEqual(retracted.map(\.1), ["draft-0"])

XCTAssertTrue(host.performFeedAction(FeedAction(id: "send", label: "Send"), key: "draft-1", on: "exchange"))
let sent = spawner.last.messages.filter { $0["type"] as? String == "action" }
XCTAssertEqual(sent.first?["feed"] as? String, "draft-1")
}

// Restarting, breaking or stopping takes the actions off its events, so
// ⏎ never shows a label nothing will answer.
func testAServiceThatGoesAwayLapsesItsFeedActions() {
tiers = ["exchange": .service]
let host = host()
var lapsed: [String] = []
host.onFeedActionsLapsed = { lapsed.append($0) }
host.load(.init(installed: [manifest("exchange", capabilities: ["feed"])]))
spawner.last.ready()
spawner.last.exit(.exited(1))
XCTAssertEqual(lapsed, ["exchange"])
XCTAssertFalse(host.canPerformFeedAction(for: "exchange"))
host.load(.init(installed: []))
XCTAssertEqual(lapsed, ["exchange", "exchange"])
}

// MARK: - Tab keys

// Actions only while running; ⌘R only once broken, as Retry.
Expand Down
170 changes: 170 additions & 0 deletions Tests/StackNudgePanelCoreTests/FeedEventTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,176 @@ final class FeedEventTests: XCTestCase {
XCTAssertEqual(store.selectedID, recovered.id, "the replacement keeps the selection it replaced")
}

// MARK: - Extension feeds

private func fromExtension(_ id: String, _ title: String = "Reply", key: String? = "draft-1",
action: FeedAction? = FeedAction(id: "send", label: "Send")) -> NudgeEvent {
.feed(source: .extension, tag: "exchange", severity: .action, title: title, message: "body",
key: key, name: "Direct exchange", extensionID: id, action: action)
}

func testAnExtensionsEventIsNamedForTheExtension() {
let event = fromExtension("exchange")
XCTAssertEqual(event.agent, "Direct exchange")
XCTAssertEqual(FeedStyle.chip(for: event), "Direct exchange")
XCTAssertEqual(event.kind, .other)
}

// A key is the poster's own name for its event: another extension, or a
// script, using the same one adds a row rather than replacing this one.
func testAKeyOnlyReplacesTheSameExtensionsEvent() {
let store = EventStore()
store.append(fromExtension("exchange", "one"))
store.append(fromExtension("other", "two"))
store.append(.feed(source: .script, tag: nil, title: "three", message: "", key: "draft-1"))
XCTAssertEqual(store.events.count, 3)
store.append(fromExtension("exchange", "four"))
XCTAssertEqual(store.events.map(\.title).sorted(), ["four", "three", "two"])
}

// Each extension has its own cap, so one can't push another's events out.
func testEachExtensionHasItsOwnCap() {
let store = EventStore()
store.append(fromExtension("quiet", "keep", key: nil))
for n in 0..<(EventStore.maxEventsPerFeed + 5) {
store.append(fromExtension("chatty", "\(n)", key: nil))
}
XCTAssertEqual(store.events.filter { $0.extensionID == "chatty" }.count, EventStore.maxEventsPerFeed)
XCTAssertEqual(store.events.filter { $0.extensionID == "quiet" }.map(\.title), ["keep"])
}

func testARetractRemovesOnlyThatExtensionsEvent() {
let store = EventStore()
store.append(fromExtension("exchange"))
store.append(fromExtension("other"))
store.retract(key: "draft-1", extensionID: "exchange")
XCTAssertEqual(store.events.compactMap(\.extensionID), ["other"])
store.retract(key: "nope", extensionID: "other")
XCTAssertEqual(store.events.count, 1)
}

// Sending marks it read and takes the action off, so a second ⏎ can't
// send it twice.
func testSendingAnActionSpendsIt() {
let store = EventStore()
let event = fromExtension("exchange")
store.append(event)
store.actionSent(id: event.id)
XCTAssertNil(store.events.first?.feedAction)
XCTAssertEqual(store.events.first?.isRead, true)
XCTAssertEqual(store.events.first?.key, "draft-1")
}

func testAnExtensionThatStopsLeavesItsEventsWithoutActions() {
let store = EventStore()
store.append(fromExtension("exchange"))
store.append(fromExtension("other"))
store.dropActions(extensionID: "exchange")
XCTAssertNil(store.events.first { $0.extensionID == "exchange" }?.feedAction)
XCTAssertNotNil(store.events.first { $0.extensionID == "other" }?.feedAction)
}

// Restored at launch with their extension and name, but never their
// action: a running extension sends its live ones again.
func testAnExtensionsEventIsRestoredWithoutItsAction() {
let posted = fromExtension("exchange")
let record = EventRecord(at: Date(), agent: posted.agent, kind: "other", title: posted.title,
message: posted.message, project: nil, session: nil,
source: "extension", tag: posted.tag, uid: posted.id.uuidString,
severity: "action", key: posted.key, extensionID: "exchange")
let store = EventStore()
store.restoreFeed(from: [record])
XCTAssertEqual(store.events.first?.extensionID, "exchange")
XCTAssertEqual(store.events.first?.agent, "Direct exchange")
XCTAssertNil(store.events.first?.feedAction)
}

// Re-posting under a key three times, then relaunching, brings back one
// row: each replacement is logged as removing the one before.
func testAReplacedEventStaysGoneAfterARelaunch() {
let path = NSTemporaryDirectory() + "sn-feed-\(UUID().uuidString).jsonl"
defer { try? FileManager.default.removeItem(atPath: path) }
let log = EventLog(path: path)
let store = EventStore()
store.log = log
for title in ["one", "two", "three"] { store.append(fromExtension("exchange", title)) }
log.flush()

let relaunched = EventStore()
relaunched.restoreFeed(from: log.load())
XCTAssertEqual(relaunched.events.map(\.title), ["three"])
}

// A log written before replacements were recorded still restores the
// newest event per poster and key only.
func testRestoringKeepsTheNewestEventPerPosterAndKey() {
func record(_ title: String, _ id: String, ago: TimeInterval) -> EventRecord {
EventRecord(at: Date().addingTimeInterval(-ago), agent: "Direct exchange", kind: "other",
title: title, message: "", project: nil, session: nil, source: "extension",
uid: UUID().uuidString, key: "draft-1", extensionID: id)
}
let store = EventStore()
store.restoreFeed(from: [record("newest", "exchange", ago: 10), record("older", "exchange", ago: 20),
record("other's", "other", ago: 30)])
XCTAssertEqual(store.events.map(\.title), ["newest", "other's"])
}

// However many feeds there are, a waiting prompt isn't pushed out by
// them: past the overall ceiling the oldest feed events go first.
func testFeedsCantPushAPromptPastTheOverallCeiling() {
let store = EventStore()
let waiting = prompt()
store.append(waiting)
for ext in 0..<6 {
for n in 0..<EventStore.maxEventsPerFeed {
store.append(fromExtension("ext\(ext)", "\(ext)-\(n)", key: nil))
}
}
XCTAssertEqual(store.events.count, 100)
XCTAssertTrue(store.events.contains { $0.id == waiting.id })
}

// An event that gained an action isn't a repeat of the one without it.
func testGainingAnActionIsNotARepeat() {
let store = EventStore()
store.append(fromExtension("exchange", action: nil))
store.append(fromExtension("exchange"))
XCTAssertEqual(store.events.first?.feedAction, FeedAction(id: "send", label: "Send"))
}

// Only ⏎ sends an extension's action, and only while it can take it.
// O, or an extension that can't answer, opens the link or is done.
func testOnlyReturnSendsTheActionAndOnlyWhenItCanBeTaken() {
let withAction = fromExtension("exchange")
XCTAssertEqual(PanelController.feedOutcome(withAction, approve: true, canSend: true), .sendAction)
XCTAssertEqual(PanelController.feedOutcome(withAction, approve: false, canSend: true), .done)
XCTAssertEqual(PanelController.feedOutcome(withAction, approve: true, canSend: false), .done)
let linked = NudgeEvent.feed(source: .extension, tag: nil, title: "t", message: "",
url: URL(string: "https://example.com"), key: "k",
name: "x", extensionID: "x", action: FeedAction(id: "send", label: "Send"))
XCTAssertEqual(PanelController.feedOutcome(linked, approve: false, canSend: true), .open)
XCTAssertEqual(PanelController.feedOutcome(feed(), approve: true, canSend: true), .open)
}

// Whatever tag it uses, an extension's row has the extension's icon and
// colour, so it can't pass as a GitHub review.
func testAnExtensionCantBorrowAnotherSourcesLook() {
let dressedUp = NudgeEvent.feed(source: .extension, tag: "review", title: "t", message: "",
name: "GitHub", extensionID: "x")
XCTAssertEqual(FeedStyle.symbol(for: dressedUp), FeedStyle.sourceSymbol(.extension))
XCTAssertEqual(FeedStyle.color(tag: "review", source: .extension), FeedStyle.sourceColor(.extension))
XCTAssertEqual(FeedStyle.symbol(for: feed()), FeedStyle.symbol(tag: "ci", source: .github))
}

// A script can't post as an extension: an extension's event can carry an
// action that ⏎ sends back to it.
func testAScriptCannotClaimToBeAnExtension() {
let event = EventListener.parseEvents(Data(#"{"agent":"x","event":"other","title":"Send","message":"m","source":"extension","key":"draft-1"}"#.utf8)).first
XCTAssertEqual(event?.source, .script)
XCTAssertNil(event?.extensionID)
XCTAssertNil(event?.feedAction)
}

func testUnkeyedFeedEventsStack() {
let store = EventStore()
store.append(feed("one", key: nil))
Expand Down
41 changes: 40 additions & 1 deletion Tests/StackNudgePanelCoreTests/ServiceProtocolTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ final class ServiceProtocolTests: XCTestCase {
XCTAssertEqual(line(.action(id: "approve", row: "d1")),
#"{"id":"approve","row":"d1","type":"action"}"# + "\n")
XCTAssertEqual(line(.action(id: "refresh", row: nil)), #"{"id":"refresh","type":"action"}"# + "\n")
XCTAssertEqual(line(.feedAction(id: "send", key: "draft-1")),
#"{"feed":"draft-1","id":"send","type":"action"}"# + "\n")
XCTAssertEqual(line(.ping(id: 17)), #"{"id":17,"type":"ping"}"# + "\n")
XCTAssertEqual(line(.stop), #"{"type":"stop"}"# + "\n")
}
Expand All @@ -54,13 +56,50 @@ final class ServiceProtocolTests: XCTestCase {
.message(.signal(name: "presence", value: "away")))
XCTAssertEqual(decode(#"{"type":"pong","id":17}"#), .message(.pong(id: 17)))
XCTAssertEqual(decode(#"{"type":"feed","event":{"title":"Left","tag":"away"}}"#),
.message(.feed(event: Data(#"{"tag":"away","title":"Left"}"#.utf8))))
.message(.feed(.init(title: "Left", message: "", tag: "away", severity: .info,
url: nil, key: nil, action: nil))))
XCTAssertEqual(decode(#"{"type":"retract","key":"draft-1"}"#), .message(.retract(key: "draft-1")))
guard case .message(.document(let document)) = decode(
#"{"type":"document","document":{"schema":1,"header":{"title":"Away"},"rows":[]}}"#)
else { return XCTFail("expected a document") }
XCTAssertEqual(document.header?.title, "Away")
}

// A feed event with an action, a severity and a link, as the exchange's
// reply drafts would post one.
func testAFeedEventWithAnActionDecodes() {
let line = #"{"type":"feed","event":{"title":"Reply for behan","message":"Looks good","tag":"exchange","severity":"action","url":"https://example.com/x","key":"draft-1","action":{"id":"send","label":"Send"}}}"#
XCTAssertEqual(decode(line), .message(.feed(.init(
title: "Reply for behan", message: "Looks good", tag: "exchange", severity: .action,
url: URL(string: "https://example.com/x"), key: "draft-1",
action: FeedAction(id: "send", label: "Send")))))
}

// Names are refused when wrong; text is trimmed to fit; a link that isn't
// a web link is dropped, as it is from a script.
func testAFeedEventIsCheckedFieldByField() {
func invalid(_ event: String) -> Bool {
if case .invalid = decode(#"{"type":"feed","event":"# + event + "}") { return true }
return false
}
XCTAssertTrue(invalid(#"{"message":"no title"}"#))
XCTAssertTrue(invalid(#"{"title":" "}"#))
XCTAssertTrue(invalid(#"{"title":"x","severity":"urgent"}"#))
XCTAssertTrue(invalid(#"{"title":"x","key":"has space"}"#))
XCTAssertTrue(invalid(#"{"title":"x","tag":"a/b"}"#))
XCTAssertTrue(invalid(#"{"title":"x","action":{"id":"send","label":"Send"}}"#), "an action needs a key")
XCTAssertTrue(invalid(#"{"title":"x","key":"k","action":{"id":"send"}}"#))
XCTAssertTrue(invalid(#"{"title":"x","key":"k","action":{"id":"","label":"Send"}}"#))
guard case .invalid = decode(#"{"type":"retract","key":""}"#) else { return XCTFail("empty retract key") }

let long = String(repeating: "a", count: 300)
guard case .message(.feed(let post)) = decode(
#"{"type":"feed","event":{"title":""# + long + #"","url":"file:///etc/passwd"}}"#)
else { return XCTFail("a long title is trimmed, not refused") }
XCTAssertEqual(post.title.count, ServiceProtocol.FeedPost.maxTitle)
XCTAssertNil(post.url)
}

// Additive: a type this host doesn't know is skipped, not an error.
func testAnUnknownTypeIsIgnored() {
XCTAssertEqual(decode(#"{"type":"telemetry","x":1}"#), .ignored(type: "telemetry"))
Expand Down
21 changes: 21 additions & 0 deletions Tests/StackNudgePanelCoreTests/ServiceSupervisorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,27 @@ final class ServiceSupervisorTests: XCTestCase {
XCTAssertEqual(sent.first?["row"] as? String, "d1")
}

// A retract needs the feed grant too: without it the extension has no
// events of its own to take back.
func testARetractWithoutTheFeedGrantIsRefused() {
_ = running()
spawner.last.say(#"{"type":"retract","key":"draft-1"}"#)
XCTAssertFalse(events.contains { if case .retract = $0 { return true } else { return false } })
XCTAssertTrue(events.contains { if case .problem = $0 { return true } else { return false } })
}

func testAFeedActionReachesOnlyARunningExtension() {
let s = supervisor(granted: [.feed])
s.start()
s.perform(feedAction: "send", key: "draft-1")
spawner.last.ready()
s.perform(feedAction: "send", key: "draft-1")
let sent = spawner.last.messages.filter { $0["type"] as? String == "action" }
XCTAssertEqual(sent.count, 1)
XCTAssertEqual(sent.first?["feed"] as? String, "draft-1")
XCTAssertEqual(sent.first?["id"] as? String, "send")
}

func testAMalformedDocumentIsReportedAsTheExtensionsBug() {
_ = running()
spawner.last.say(#"{"type":"document","document":{"schema":9}}"#)
Expand Down
26 changes: 23 additions & 3 deletions docs/design/service-extensions.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,17 +143,37 @@ no capability. Additive: an extension that predates it skips the type.
{"type": "document", "document": { "schema": 1, "header": {}, "rows": [] }}
{"type": "signal", "name": "presence", "value": "away"}
{"type": "feed", "event": { "title": "Left the desk", "tag": "away", "severity": "info" }}
{"type": "feed", "event": { "title": "Reply for Sam", "message": "Looks good", "key": "draft-1", "action": { "id": "send", "label": "Send" } }}
{"type": "retract", "key": "draft-1"}
{"type": "pong", "id": 17}
{"type": "choices", "key": "STACKNUDGE_EXT_AWAY_PHONE", "options": [{"value": "Pixel", "label": "Pixel · −70 dBm"}]}
```

- `document` replaces the tab's document, with the same schema and caps as a view
extension's stdout today (8 MB).
- `signal` sets a named value the app's features read. See [Signals](#signals).
- `feed` (*not yet delivered*: the host accepts the line and logs it) posts a feed event on the same path as the socket's
- `feed` posts a feed event to Events, on the same path as the socket's
`"source":"script"` events (#235), so it can never be a permission prompt. It
gets its own source, `extension:<id>`, with its own cap of 20, so an extension
can't push the user's own script events out of the queue.
comes from source `extension`, named for the extension, with a cap of 20 per
extension, so one can't push the user's own events or another extension's out
of the queue. A socket script that claims that source is read as `script`. `title` is required;
`message` (up to 4,096 characters, trimmed), `tag`, `severity` (`info`,
`action`, `alert`), `url` (web links only, as from a script) and `key` are
optional. A `key` replaces this extension's earlier event with the same key,
never another poster's.
- An event with a `key` may carry one `action`, `{"id", "label"}`. `⏎` on it in
Events, labelled with `label`, sends `{"type": "action", "id": "send", "feed":
"draft-1"}` back instead of opening the link (`O` still opens it, and never
sends). Its row keeps the extension's icon and colour whatever its tag, so it
can't pass as another source's. Sending marks it read and takes
the action off, so a second `⏎` can't send it twice: the extension replaces or
retracts the event once it has acted. A banner click never sends it. When the
extension stops, restarts or breaks, its events lose their actions and act as
ordinary feed events until it posts them again; actions aren't kept in the
event log, so a restored event has none either.
- `retract` takes this extension's event with that `key` out of Events, for
when what it stood for was dealt with elsewhere. Both need the `feed`
capability.
- `choices` offers the values a `dynamic` config key may take right now, for its
Settings picker (see [Where an extension appears](#where-an-extension-appears)).
Kept only for a key the manifest declared as `dynamic`; at most 64 options,
Expand Down
Loading
Loading