# Friends

Unity GameKit routes friend operations through the attached, signed-in Desktop
Host. Desktop owns authentication, backend actions and relationship policy.

Install Core before GameKit, using the same SDK version and one carrier per
module. Create and fill an IGPConfig (including appId), assign it to an
IGPRuntimeManager, then initialize that component as shown in [QUICKSTART.md](QUICKSTART.md).
Friends needs no IGPGameKitRuntime component. With the configured runtime reference:

```csharp
using IGP.UnitySDK.GameKit;

await runtimeManager.InitializeAsync();
var friends = await IGPFriends.GetFriendsAsync(runtimeManager);

var sent = await IGPFriends.SendFriendRequestAsync(runtimeManager, targetUserId);
// sent.result: REQUEST_SENT, REQUEST_RESENT, or AUTO_ACCEPTED.

var incoming = await IGPFriends.GetIncomingFriendRequestsAsync(runtimeManager);
foreach (var request in incoming)
{
    // Display request.profile, request.note and request.requestedAt.
    // Retain request.friendshipId for an explicit Accept button.
}

// Call only after the player chooses to accept this request:
var accepted = await IGPFriends.AcceptFriendRequestAsync(
    runtimeManager, selectedRequest.friendshipId);
// accepted.result: ACCEPTED.
```

Each new method accepts an optional final `CancellationToken`. The existing
`GetFriendsAsync(runtimeManager)` API remains unchanged.

## Data reference

All result objects are independent snapshots. Constructed DTO defaults are not
successful Host results; consume the values returned by the query/action methods.

| Type / field | C# type | Default / optionality | Meaning |
| --- | --- | --- | --- |
| IGPFriendRequestActionResult.result | string | Empty on construction; required in responses | Host action outcome |
| IGPIncomingFriendRequest.friendshipId | string | Empty on construction; required in responses | Relationship ID used to accept |
| IGPIncomingFriendRequest.profile | IGPPlayerProfile | New profile on construction; required | Request sender |
| IGPIncomingFriendRequest.note | string? | null; nullable | Sender's optional note |
| IGPIncomingFriendRequest.requestedAt | string? | null; nullable | Host timestamp, without local inference |
| IGPPlayerProfile.id | string | Empty on construction; required in responses | User ID |
| IGPPlayerProfile.nickname | string? | null; nullable | Display nickname |
| IGPPlayerProfile.avatarUrl | string? | null; nullable | Avatar URL |
| IGPPlayerProfile.avatarFrameUrl | string? | null; nullable | Static frame URL |
| IGPPlayerProfile.subscriptionBenefitsActive | bool? | null in friend snapshots | Unknown membership benefits |
| IGPFriend.profile | IGPPlayerProfile | New profile; required in responses | Friend's profile |
| IGPFriend.onlineStatus | IGPFriendOnlineStatus | Offline (0) | Offline includes unconfirmed presence; Online is 1 |

| Operation | Input | Result |
| --- | --- | --- |
| SendFriendRequestAsync | Target player user ID | `IGPFriendRequestActionResult.result`, the Host outcome string |
| GetIncomingFriendRequestsAsync | None | Fresh `IGPIncomingFriendRequest[]` snapshot |
| AcceptFriendRequestAsync | Friendship ID from the incoming snapshot | `IGPFriendRequestActionResult.result` |

An incoming request contains `friendshipId`, `profile`, nullable `note`, and
nullable `requestedAt`. The profile contains `id` and nullable nickname/avatar
URLs. `requestedAt` preserves the Host timestamp string. Fetching does not mark
requests viewed. These query/action methods do not subscribe, poll, mutate caches,
retry automatically or emit events. Presence monitoring is a separate opt-in API below.

Sending may auto-accept a reciprocal pending request under the existing backend
policy. The SDK preserves that outcome; it does not assume every send stays pending.
Accept uses the relationship ID, which is different from `profile.id`.

Failures throw `IGPFriendsException` with a safe `Code`, including
`FRIENDS_INVALID_INPUT`, `FRIENDS_INVALID_RESPONSE`, `FRIENDS_TIMEOUT`,
`AUTH_SESSION_CHANGED`, or the Host's stable command/business failure code.
Unsupported commands on older Desktop versions fail rather than returning a
fabricated success or empty list. Cancellation throws `OperationCanceledException`
and cannot undo an action already sent. After an uncertain mutation outcome,
refresh the friend/request snapshots before deciding whether to retry.

Host must support commands 27 (send), 28 (incoming) and 29 (accept). Shared JSON
schemas live in `igp-proto/jsonschema/desktop-session/`. These APIs currently apply
to Unity; other engine bindings do not expose the new operations.

## Explicit presence monitoring

Create `IGPFriendMonitor` on Unity's main thread after the configured runtime has
attached. It requires only Core and GameKit, without an IGPGameKitRuntime component.
One runtime may have one active monitor. Start/stop have no parameters and repeated
calls are idempotent. Stop before discarding the monitor.

```csharp
var monitor = new IGPFriendMonitor(runtimeManager);
monitor.FriendStatusChanged += change =>
{
    // Look up change.UserId in your game's friend list, then update that row.
    // change.IsOnline and change.IsDesktopOnline are separate states.
};
await monitor.StartAsync();

// In your UI's Update, read monitor.CurrentSnapshot for initial state/readiness.
// StartAsync confirms subscription; the first snapshot may arrive later.
// Only Status == IGPFriendPresenceStatus.Ready is current presence information.

// When the game no longer needs presence:
await monitor.StopAsync();
```

`CurrentSnapshot` has read-only Status, OnlineUserIds and DesktopOnlineUserIds.
It is null before the first valid snapshot and after stop/session end. Status is
Idle (0), Loading (1), Ready (2), or Error (3). Collections cannot be modified by
the caller. The initial Ready snapshot does not create artificial online events.

`FriendStatusChanged` exposes UserId, WasOnline, IsOnline, WasDesktopOnline and
IsDesktopOnline. The snapshot is updated before callbacks run on the Unity main
thread. Unchanged snapshots and older revisions do not emit events; handler
exceptions do not prevent other handlers running. Non-ready state is unknown,
not all friends offline. After recovery the first Ready snapshot is a new baseline.
Events are not replayed to later handlers.

Session end clears the monitor. After a new session attaches, call StartAsync
explicitly again. No SDK timer or automatic reconnect is involved. Desktop must
support command 30 and Service Message 10; an unsupported Host fails with
IGPFriendsException instead of silently polling. Local errors include
FRIENDS_MONITOR_ALREADY_ACTIVE, FRIENDS_MAIN_THREAD_REQUIRED,
FRIENDS_SESSION_ENDED, FRIENDS_SUBSCRIPTION_FAILED and FRIENDS_UNSUBSCRIBE_FAILED.

The stream is the Host-visible presence projection, not a friend membership list.
Use IGPFriends.GetFriendsAsync for profiles and friend membership. This preserves
its existing behavior (unconfirmed online status is Offline); do not treat that
query fallback as a presence transition. Lying Bottle does not reference GameKit:
the game subscribes here and connects UI/business interactions to Lying Bottle.
Online status alone does not establish invitation eligibility.
