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
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,10 @@ push to main
| Tool | What it does |
|---|---|
| `get_import_format` | Item fields, rules, and an example |
| `list_status_sheet` | The owner's current items |
| `propose_status_sheet_import` | Validates items into a proposal (24 h); changes nothing |
| `list_aircraft` | The owner's aircraft (each has its own Status Sheet) |
| `add_aircraft` | Adds an empty aircraft; same rules as the dashboard (tail number unique per account, up to 25). Doesn't change which aircraft the dashboard opens on |
| `list_status_sheet` | One aircraft's current items |
| `propose_status_sheet_import` | Validates items into a proposal for one aircraft (24 h); changes nothing. With `recordsTailNumber`, refuses records for a plane that isn't on the account or isn't the target |
| `continue_poor_fit` | Continues a proposal where most rows didn't fit, after the owner agrees |
| `confirm_status_sheet_import` | Adds exactly the proposal's items, all or nothing |
| `list_flights` | The owner's logged flights |
Expand Down
2 changes: 1 addition & 1 deletion docs/backend-notes/HTTP.txt
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ cached resources and the browser can ignore them.
by using the WWW-Authenticate and similar headers. Or by setting a specific session by using HTTP cookies.
3.relaxing the origin constraint - to prevent snooping and other privacy invasions web browsers enforce strict seperation between
websites. Only pages from the same origin can access all information from a web page. This can be limiting to some web apps / servers so relaxing the origin constraints relaxes this by allowing other domains to talk to your
server. In this project I don't have multiple domains talking to my server so CORS is not required.
server. In this project most pages are same-origin, so they don't need CORS. The one exception is /api/public/**: my portfolio site (danielibarra.com) reads /api/public/stats from another origin, so SecurityConfig allows that origin with CORS (GET only).
4.proxy and tunneling
5.sessions

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,38 @@ void removeAircraftNeedsTheTailNumber() {
assertThat(page.locator("#remove-aircraft-btn")).hasText("Remove N2BB…");
page.locator("#remove-aircraft-btn").click();
assertThat(page.locator("#remove-aircraft-dialog")).isVisible();
assertThat(page.locator("#remove-aircraft-ok")).isDisabled();
assertThat(page.locator("#remove-aircraft-ok")).isEnabled();
page.locator("#remove-aircraft-confirm").fill("n2 bb");
assertThat(page.locator("#remove-aircraft-ok")).isEnabled();
page.locator("#remove-aircraft-ok").click();
page.waitForURL(baseUrl() + "/dashboard?aircraft=" + a.getId());
assertTrue(aircraftRepository.findById(b.getId()).isEmpty());
assertEquals(List.of("Alpha Annual", "Alpha Oil"), visibleItems(page));
}

// Spec 012 US1: a click on Remove is never silent. Wrong text says what
// to type and sends nothing.
@Test
void removeAircraftWrongTextSaysWhatToType() {
seedFleet();
loginAs(username, "password");
page.navigate(baseUrl() + "/dashboard?aircraft=" + b.getId());
List<String> deletes = new java.util.ArrayList<>();
page.onRequest(r -> { if ("DELETE".equals(r.method()) && r.url().contains("/aircraft/")) deletes.add(r.url()); });
page.locator("#aircraft-picker-btn").click();
page.locator("#remove-aircraft-btn").click();
assertThat(page.locator("label[for='remove-aircraft-confirm']")).hasText("Type the tail number, N2BB, to confirm");
assertThat(page.locator("#remove-aircraft-ok")).isEnabled();

page.locator("#remove-aircraft-ok").click();
assertThat(page.locator("#remove-aircraft-error")).hasText("Type N2BB to confirm");

page.locator("#remove-aircraft-confirm").fill("N1AA");
assertThat(page.locator("#remove-aircraft-error")).hasText("");
page.locator("#remove-aircraft-confirm").press("Enter");
assertThat(page.locator("#remove-aircraft-error")).hasText("Type N2BB to confirm");

assertTrue(deletes.isEmpty());
assertTrue(aircraftRepository.findById(b.getId()).isPresent());
}
}
3 changes: 3 additions & 0 deletions src/browserTest/resources/application-browsertest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ spring:
username: sa
password:
jpa:
# Same as Heroku (application-heroku.properties), so browser tests catch
# lazy-loading bugs that only show in production (spec 012 R1).
open-in-view: false
hibernate:
ddl-auto: create-drop
properties:
Expand Down
65 changes: 57 additions & 8 deletions src/main/java/com/example/AviaryService/mcp/AircraftTools.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,91 @@
import java.util.List;

import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Component;

import com.example.AviaryService.entity.Aircraft;
import com.example.AviaryService.entity.User;
import com.example.AviaryService.oauth.CimdRegisteredClientRepository;
import com.example.AviaryService.repositories.AircraftRepository;
import com.example.AviaryService.repositories.StatusSheetItemRepository;
import com.example.AviaryService.services.aircraft.AircraftLimitException;
import com.example.AviaryService.services.aircraft.AircraftService;
import com.example.AviaryService.services.aircraft.AircraftValidationException;
import com.example.AviaryService.util.Validation;

// MCP tool listing the owner's aircraft, so an assistant can ask which one an
// import is for and pass it as `aircraft` to the other tools.
// MCP tools for the owner's fleet: list_aircraft, so an assistant can ask
// which one an import is for and pass it as `aircraft` to the other tools,
// and add_aircraft (spec 012), so records for a plane that isn't on the
// account yet get their own aircraft instead of landing on another one.
@Component
public class AircraftTools {

public record AircraftSummary(Long aircraftId, String tailNumber, String makeModel,
Double timeInServiceHours, long statusSheetItems) {}

// status: ADDED, ALREADY_EXISTS, INVALID or LIMIT_REACHED. aircraft is
// the new one (ADDED), the existing one (ALREADY_EXISTS), otherwise null.
public record AddAircraftResult(String status, String message, AircraftSummary aircraft) {}

private final AircraftRepository aircraftRepository;
private final StatusSheetItemRepository statusSheetItemRepository;
private final AircraftService aircraftService;
private final McpCurrentUser currentUser;

public AircraftTools(AircraftRepository aircraftRepository, StatusSheetItemRepository statusSheetItemRepository,
McpCurrentUser currentUser) {
AircraftService aircraftService, McpCurrentUser currentUser) {
this.aircraftRepository = aircraftRepository;
this.statusSheetItemRepository = statusSheetItemRepository;
this.aircraftService = aircraftService;
this.currentUser = currentUser;
}

@Tool(name = "list_aircraft", description = """
The owner's aircraft. When there is more than one, ask the owner which aircraft their records are for \
and pass its tail number (or aircraftId) as `aircraft` to list_status_sheet, list_flights and \
propose_status_sheet_import.""")
propose_status_sheet_import. If the owner's records are for a plane that isn't listed, add it with \
add_aircraft first.""")
public List<AircraftSummary> listAircraft() {
currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ);
User user = currentUser.require();
return aircraftRepository.findByUserOrderByIdAsc(user).stream()
.map(a -> new AircraftSummary(a.getId(), a.getTailNumber(), a.getMakeModel(),
a.getTimeInServiceHours(), statusSheetItemRepository.countByAircraft(a)))
.toList();
return aircraftRepository.findByUserOrderByIdAsc(user).stream().map(this::summary).toList();
}

@Tool(name = "add_aircraft", description = """
Add an aircraft to the owner's account. Use it when the owner's records are for a plane that isn't in \
list_aircraft yet, then pass the returned tail number as `aircraft` (and `recordsTailNumber`) to \
propose_status_sheet_import. The new aircraft starts empty. Doesn't change which aircraft the owner's \
dashboard opens on. If the tail number is already on the account, returns ALREADY_EXISTS with that \
aircraft: import into it instead.""")
public AddAircraftResult addAircraft(
@ToolParam(description = "The aircraft's tail number, e.g. N731KR") String tailNumber,
@ToolParam(description = "Make and model, e.g. Piper PA-28", required = false) String makeModel,
@ToolParam(description = "Operator name", required = false) String operatorName,
@ToolParam(description = "Serial number", required = false) String serialNumber) {
currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT);
User user = currentUser.require();
String key = Validation.tailNumberKey(tailNumber);
if (key != null) {
var existing = aircraftRepository.findByUserAndTailNumberKey(user, key);
if (existing.isPresent()) {
Aircraft a = existing.get();
return new AddAircraftResult("ALREADY_EXISTS", a.getDisplayName() + " is already on this account (aircraftId "
+ a.getId() + "). Import into it instead.", summary(a));
}
}
try {
Aircraft created = aircraftService.create(user, tailNumber, makeModel, operatorName, serialNumber, false);
return new AddAircraftResult("ADDED", "Added " + created.getDisplayName() + ".", summary(created));
} catch (AircraftLimitException e) {
return new AddAircraftResult("LIMIT_REACHED", e.getMessage(), null);
} catch (AircraftValidationException e) {
return new AddAircraftResult("INVALID", e.getMessage(), null);
}
}

private AircraftSummary summary(Aircraft a) {
return new AircraftSummary(a.getId(), a.getTailNumber(), a.getMakeModel(),
a.getTimeInServiceHours(), statusSheetItemRepository.countByAircraft(a));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ public AircraftChoiceException(String message) {
}
}

// The records name a plane this account doesn't have (spec 012 US2).
public static class AddAircraftFirstException extends AircraftChoiceException {
public AddAircraftFirstException(String message) {
super(message);
}
}

// The named aircraft and the records' tail number are different planes.
public static class AircraftMismatchException extends AircraftChoiceException {
public AircraftMismatchException(String message) {
super(message);
}
}

private final AircraftRepository aircraftRepository;

public McpAircraftResolver(AircraftRepository aircraftRepository) {
Expand Down Expand Up @@ -56,6 +70,27 @@ public Aircraft resolve(User user, String aircraft) {
+ describe(fleet) + ".");
}

// As resolve(user, aircraft), plus the tail number the owner's records
// are for. When given, records only ever go to that plane: missing ->
// AddAircraftFirstException (even on a one-aircraft account, which would
// otherwise take anything), a different named aircraft ->
// AircraftMismatchException. Only this owner's aircraft are searched.
public Aircraft resolve(User user, String aircraft, String recordsTailNumber) {
String recordsKey = Validation.tailNumberKey(recordsTailNumber);
if (recordsKey == null) return resolve(user, aircraft);
String recordsTail = recordsTailNumber.trim();
Aircraft forRecords = aircraftRepository.findByUserAndTailNumberKey(user, recordsKey)
.orElseThrow(() -> new AddAircraftFirstException("These records are for " + recordsTail
+ ", which isn't on this account. Add it with add_aircraft, then import into it."));
if (aircraft == null || aircraft.isBlank()) return forRecords;
Aircraft named = resolve(user, aircraft);
if (!named.getId().equals(forRecords.getId())) {
throw new AircraftMismatchException("You asked to import into " + named.getDisplayName()
+ ", but these records are for " + forRecords.getDisplayName() + ".");
}
return named;
}

// "N482DM (Cessna 172S), N731KR (Piper PA-28)"
static String describe(List<Aircraft> fleet) {
return fleet.stream().map(a -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,10 @@ public StatusSheetImportTools(StatusSheetImportService importService, StatusShee
@Tool(name = "get_import_format", description = """
How Aviary Status Sheet items must look, with the rules and an example. Call this first, then \
convert the owner's maintenance records (any format) into these items before proposing. Each aircraft \
has its own statusSheetItem: if list_aircraft shows more than one, ask the owner which aircraft the records \
are for and pass it as `aircraft`.""")
has its own Status Sheet. Look for the tail number in the owner's records (often in the title or header). \
If it isn't in list_aircraft, add it with add_aircraft, then propose with `aircraft` and `recordsTailNumber` \
set to it. If the records name no plane and list_aircraft shows more than one, ask the owner which aircraft \
the records are for. Records for several planes: one add (if needed) and one proposal per plane.""")
public ImportFormat getImportFormat() {
currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ);
Map<String, String> fields = new LinkedHashMap<>();
Expand Down Expand Up @@ -93,23 +95,38 @@ public List<StatusSheetRow> listStatusSheetItem(
only needs a name. Changes nothing: returns a proposal with the items as Aviary would store them, flags \
and notes for the owner to check, and rows that can't be imported with reasons. Show the owner the \
proposal before confirming. Calling this again for the same aircraft replaces the previous proposal \
(use it to revise).""")
(use it to revise). Pass `recordsTailNumber` when the records name a plane: records are never imported \
into a different plane, and a plane that isn't on the account must be added with add_aircraft first.""")
public ImportResult proposeStatusSheetImport(
@ToolParam(description = "Items converted from the owner's records; see get_import_format") List<InputItem> items,
@ToolParam(description = "Rows that are not maintenance items at all, each with a reason. Never put a real item here just because it has no dates.", required = false)
List<RejectedRow> rejectedBySource,
@ToolParam(description = AIRCRAFT_PARAM, required = false) String aircraft) {
@ToolParam(description = AIRCRAFT_PARAM, required = false) String aircraft,
@ToolParam(description = "The tail number the owner's records are for, if the records or the owner name one. "
+ "Aviary refuses to import them into a different plane.", required = false)
String recordsTailNumber) {
currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT);
User user = currentUser.require();
Aircraft target;
try {
target = aircraftResolver.resolve(user, aircraft);
target = aircraftResolver.resolve(user, aircraft, recordsTailNumber);
} catch (McpAircraftResolver.AddAircraftFirstException e) {
return ImportResult.addAircraftFirst(e.getMessage());
} catch (McpAircraftResolver.AircraftMismatchException e) {
return ImportResult.mismatch(e.getMessage());
} catch (McpAircraftResolver.AircraftChoiceException e) {
return ImportResult.choose(e.getMessage());
}
return importService.propose(user, target, items, rejectedBySource, currentUser.clientId());
}

// Not a tool: the pre-012 call shape, kept for callers that don't pass
// the records' tail number.
public ImportResult proposeStatusSheetImport(List<InputItem> items, List<RejectedRow> rejectedBySource,
String aircraft) {
return proposeStatusSheetImport(items, rejectedBySource, aircraft, null);
}

@Tool(name = "continue_poor_fit", description = """
For a POOR_FIT proposal: the owner agreed to continue with only the rows that fit. Returns the proposal, \
which can then be confirmed.""")
Expand All @@ -132,7 +149,7 @@ public ImportResult confirmStatusSheetImport(
}

static final String AIRCRAFT_PARAM =
"Tail number or aircraftId from list_aircraft. Required when the owner has more than one aircraft.";
"Tail number or aircraftId from list_aircraft or add_aircraft. Required when the owner has more than one aircraft.";

private static String join(String date, String hours) {
String d = date == null ? "" : date;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ public interface AircraftRepository extends JpaRepository<Aircraft, Long> {
Optional<Aircraft> findFirstByUserOrderByIdAsc(User user);
long countByUser(User user);
boolean existsByUserAndTailNumberKey(User user, String tailNumberKey);
Optional<Aircraft> findByUserAndTailNumberKey(User user, String tailNumberKey);
boolean existsByUserAndTailNumberKeyAndIdNot(User user, String tailNumberKey, Long id);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.AviaryService.services.aircraft;

// The account already has Aircraft.MAX_PER_USER aircraft. Still shown under
// the tail number field on the dashboard; the MCP add_aircraft tool reports
// it as LIMIT_REACHED.
public class AircraftLimitException extends AircraftValidationException {
public AircraftLimitException(String message) {
super("tailNumber", message);
}
}
Loading
Loading